How to compare every element of list with one another?

I have two string lists lst1 and lst2. I want to compare every element from lst1 with every element from lst2 by using List operations such as List.map, List.filter.

In other languages, I would just use nested for loops but what should I do in OCaml?

2 answers

  • answered 2018-02-13 00:42 Roma149

    I don't know OCaml, but it seems that you're looking for the functional way to compare two arrays. In this case, I would use something like the zip function that is present in many languages, which creates a new array in which each element is an array containing the elements of the input arrays at that index. In OCaml this seems to be List.combine.

    So, for example, zipping [1,2,3] and [4,5,6] yields [[1,4],[2,5],[3,6]].

    This allows you to use map or filter to do a comparison for each pair.

    For example, in Ruby I'd do something like this:

    [1,2,3].zip([4,5,6]).map { |x,y| x > y ? x : y }
    

    Sorry it's not a complete answer, but I hope it helps.

  • answered 2018-02-13 00:42 drilow

    If the Lists are guaranteed to be the same length, OCaml has:

    List.fold_left2 (fun a e1 e2 -> a and (e1=e2)) true lst1 lst2
    

    Or, equivalent to the answer provided by @Roma149:

    (List.combine lst1 lst2) |> (List.fold_left (fun a (e1,e2) -> a and e1=e2) true)
    

    But of course, OCaml defines structural equality for every type, so you should probably just go for:

    lst1 = lst2