Gasim
Gasim

Reputation: 8001

ocaml - iterate values two by two in a list

Is there a way to iterate over a list in two values? Something like:

let my_list : int list = [1;2;3;4;5;6;7];;

let iterate_by_two elem1 elem2 = 
    if elem1 < elem2 then Printf.printf "True"
    else Printf.printf "False"
in List.iter iterate_by_two my_list;;

List.iter only accepts a function with one argument that is the element. Is there another function that I should look into?

Upvotes: 2

Views: 1169

Answers (3)

Jbeuh
Jbeuh

Reputation: 395

If you're not hell-bent on using fold or iter, it's probably easiest to just write what you mean :

let rec iter_pairs f lst = 
  match lst with 
      [] | [_] -> ()
    | x::y::tl -> (f x y;
                   iter_pairs f (y::tl))

Upvotes: 2

Benjamin Barenblat
Benjamin Barenblat

Reputation: 1311

No, but it’s easy to write one:

let fold_left1 f lst = List.fold_left f (List.hd lst) (List.tl lst);;

let iter_pairs f lst =
  let folder left right =
    let () = f left right in
    right
  in
  ignore (fold_left1 folder lst);;

Now, you can write iter_pairs iterate_by_two my_list.

Upvotes: 1

Tarmil
Tarmil

Reputation: 11372

You can use List.iter2, which iterates over two lists in parallel, with your list and its own tail.

It throws an exception if the lists have different lengths, which is going to be the case here since the tail is obviously one element shorter, but exceptions in OCaml are cheap to catch so it's not a problem.

try
  List.iter2 iterate_by_two my_list (List.tl my_list)
with Invalid_argument _ -> ()

Upvotes: 2

Related Questions