I am trying to implement a function which takes in an int and a list of numbers, and check if all elements of the list is divisible by the int, for example:div_by_x 2 [1;3;4;8;0] = [false;false;true;true;true] I have a helper function which just returns true or false when viable:
let divisible x i =
if i mod x = 0 then true else false;;
With that, I have already implemented a working recursive div function, which is:
let rec div_by_x x y = match y with
[] -> []
| (hd :: tl) ->
let l1 = div_by_x x tl in divisible x hd :: l1;;
But now I am trying to implement div_by_x with the fold function, defined as:
let rec fold f a l = match l with
[] -> a
| (h::t) -> fold f (f a h) t
;;
I am kinda stuck on how to make the list while keeping the on going list. So far I have
let div_by_x x y= fold divisible x y [] y;;
which doesnt seem to work and yells at me with: "
Error: This expression has type int -> int -> bool but an expression was expected of type ('a -> 'b -> 'c) -> 'd -> 'a -> 'b -> 'c Type int is not compatible with type 'a -> 'b -> 'c "
Any help? Thanks!
if expression then true else false
can be replaced byexpression
alone. – PatJdivisible x
to each element of the list. This can be accomplished usingmap
. You now have to implementmap
in terms offold
. :) – gallais