Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding two list in OCaml

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading