Reputation: 31
I've to write a anonymous function that take a list of integer and two functions f and g.The function apply f on the even int in the list and apply g on the odd int. finally the function return the sum of all computed values..f(x)=2x,g(x)=x*x
my code is
val f = fn x => 2 * x;
val g = fn x => x * x;
fun s [] f g = []
| s L f g =
let
val n = hd(L) mod 2;
in
fn n => case n of
0 => f(hd(L)) + s tl(L) f g
| x => g(hd(L)) + s tl(L) f g
end;
what is wrong??
Upvotes: 3
Views: 1077
Reputation: 41290
First, you should put parentheses around tl(L)
so the invoke of s (tl(L)) f g
is parsed correctly. Second, the return type of the function is int
so the base case []
should return 0
and the inductive case shouldn't have fn n =>
(because n
is already defined by val
).
I refactored the function using pattern matching instead of hd
, tl
and put the frequent changing argument as the last one:
fun sum f g [] = 0
| sum f g (x::xs) =
let
val n = x mod 2
in
case n of
0 => f x + sum f g xs
| _ => g x + sum f g xs
end;
Upvotes: 2