Vuka
Vuka

Reputation: 7

Matching arithemtic operations with a list of lists in OCaml

I'm facing a problem in OCaml where I need to perform arithmetic operations on a list of lists. As parameters I'm passing the list of lists, for example [[1;2;3]; [4;5;6]];, and a list of characters like this ['+'; '*'; '-'].

This is what I have so far:

let addition = List.map (List.fold_left ( + ) 0);;
let multiplication = List.map (List.fold_left ( * ) 0);;
let subtraction = List.map (List.fold_left ( - ) 0);;

let list = [[1;2;3]; [4;5;6]; [7;8;9]];;
let operators = ['+'; '*'; '-'];;

let rec rows l o =
  match (l, o) with
    ([], []) -> []
    (hd::tl, op::tlo) ->
      (
        match hd with
          [] -> 0::(rows tl tlo)
          h::t ->

This is the missing part, I don't know how to match the first operator with the first list in the list of lists, the second operator with the second list of lists and so on and to perform the operation on the elements in the list.

I tried with using List.iter to go through each operator but I got confused on how to match the positions in the operator list with the list of lists.

With the given list of lists and the given operators, the result should be [6; 120; -10].

I'm quite new to OCaml, I'm sorry if I missed something very obvious, any help is dearly appreciated.

Upvotes: 0

Views: 221

Answers (1)

ivg
ivg

Reputation: 35210

You can map two lists in parallel, assuming that the are of the same length

 let rec map2 f xs ys = match xs,ys with
   | [], [] -> []
   | x :: xs, y :: ys -> f x y :: map2 f xs ys
   | _ -> invalid_arg "map2: list length mismatch"

This function is pretty straightforward - given the function f and two list with equal length [x1; ...; xM] and [y1;...;yM] it constructs a new list in which i-th element is the result of f xi yi, i.e., [f x1 y1; ...; f xM yM]. For example, we can now take a list of operators and a list of integer lists, and reduce each list using the corresponding operator:

# map2 (fun op -> List.fold_left op 0) [(+); (-)] [[1;2;3]; [3;2;1]];;
- : int list = [6; -6]

I think from here you can fill in the blanks :)

And my advice, don't try to solve your problem with one big function that does everything at once, try to make small bites of the problem, bites that you can chew. This is the essence of functional (and any other) programming - writing small composable functions. Split the task into small subtasks, solve each, then combine.

Upvotes: 0

Related Questions