Hylomorphism and Euler problem 2
In my recent posts I've played with Euler problem 2 and hylomorphism: here I use the hylomorphism concept to solve the Euler problem 2 using Ocaml :)
(* Given a hylomorphism implementation ...*)
let rec hylo_impl step till col inj v s =
if till s
then v
else
let ns = step s in
let nv = inj (col s) v in
hylo_impl step till col inj nv ns
;;
(* ... solving Euler problem 2 is quite easy! *)
let eul2 n =
hylo_impl
(fun (n0, n1) -> (n1, n0 + n1))
(fun (n0, n1) -> n0 > n)
(fun (n0, n1) -> if n0 mod 2 == 0 then n0 else 0)
(fun x a -> x + a)
0
(1, 1)
;;
This time I tried to add default value with labels notation of Ocaml. But I have a problem with type inference: if the given default function has a type, all function I pass as parameter must have the same type as the default one ... still have to learn a bit more about polymorphism in ocaml I presume ;). The following code may work in some case, but it forces the type of the functions, which is really bad! Any advice to solve this problem?
let hylo
?(step = fun x -> x + 1)
?(till = fun x -> true)
?(col = fun x -> x)
?(inj = ((fun x a -> x :: a), []))
s
=
let (injf, injv) = inj in
hylo_impl step till col injf injv s
;;
Post imported from wordpress
Please refer to original post for earlier comments.