i'm learning scala working exercises book "scala impatient". there're few questions test concept of currying. i've answered them best of understanding i'd run experts here.
make call
corresponds
checks whether elements in array of strings have lengths given in array of integers.
my code:
def iscorrespondinglength(arr: array[string], len: array[int]) = { arr.corresponds(len)(_.length == _) }
implement
corresponds
without currying. try call previous exercise. problem encounter?
ans: compiler can't derive type using underscores in previous exercise.
def mycorresponds(arr: array[string], that: seq[int], f: (string, int) => boolean) = { arr.zip(that).find(p => f.apply(p._1, p._2)).isdefined }
implement
unless
control abstraction worksif
, inverted condition. first parameter need call-by-name parameter? need currying?
ans: first parameter doesn't need call-by-name parameter. since it's evaluated once, whether evaluation happens @ call site (as in call-by-value) or inside function (call-by-name) doesn't affect outcome. currying, in unless2
, provides nice control abstraction unless2(false) { block }
it's not necessary.
def unless(condition: () => boolean, block: => boolean): boolean = { if (!condition()) block else false } def unless2(condition: => boolean)(block: => boolean): boolean = { if (!condition) block else false }
def iscorrespondinglength(arr: array[string], len: array[int]) = { mycorresponds(arr, len, _.length == _) }
compiles fine. consider happens if make mycorresponds
generic (i.e. work a
, b
rather string
, int
).
Comments
Post a Comment