let rec add_lists (xs : float list) (ys : float list): float list option =
match xs ys with
| ([],[]) -> Some[]
| (x::xs', []) -> None
| ([],y::ys') -> None
| hd::tl ->
(match xs ys with
|[] -> None
|hd2 :: tl2 ->(hd+hd2):: (add_lists tl tl2)
)
I wanted to add 2 list together. To add the elements of two lists together,
if they are different lengths return None.
Examples:
add_lists [1.; 2.] [3.; 4.] = Some([4.; 6.])
add_lists [] [1.2] = None
>Solution :
let add_lists (xs : float list) (ys : float list): float list option =
let rec aux acc first second =
match first, second with
| [], [] -> Some(acc)
| [], hd::tl -> None
| hd::tl, [] -> None
| hd::tl, hd'::tl' -> aux ((hd +. hd')::acc) (List.tl first) (List.tl second)
in
let res = aux [] xs ys in
match res with
| Some(x) -> print_string "Returned"; Some(List.rev x)
| None -> print_string "Lists not same length"; None
Works with the good output.
Edit: Tail Recursive so you get good grades 🙂