Tartar
Tartar

Reputation: 5452

F#: integers to pair of integers

I have function that takes a list of integers as an argument and returns a list of pairs as a result. For example the [1;2;3;4] should be returned as [(1, 2); (3, 4)]

I have implemented the below function for this.

let listToPairList (list: int list) = 
  let index,pairList = List.foldBack(fun elem (iAcc,listAcc) -> 
    if (iAcc % 2 = 0) then
      (iAcc - 1,(elem,list.[iAcc + 1])::listAcc)
    else
      (iAcc - 1,listAcc)) list (list.Length - 1, [])
  pairList

Now ,I want to do it with using foldBack function but without using indexes. Could anyone give me an idea about how to make it ?

Any help would be appreciated.

Upvotes: 0

Views: 101

Answers (2)

gileCAD
gileCAD

Reputation: 2493

Why using foldback?

What about a simple recursive function

let rec listToPairList = function
    | []       -> []
    | x::[]    -> [(x,x)]
    | x::y::xs -> (x,y)::listToPairList xs

Or a tail recursive one:

let listToPairList lst =
    let rec aux acc = function
        | []         -> acc |> List.rev
        | x::[]      -> (x,x)::acc |> List.rev
        | x1::x2::xs -> aux ((x1,x2)::acc) xs
    aux [] lst

Upvotes: 3

Lee
Lee

Reputation: 144136

You could use an int option to track the next item in through the fold:

let listToPairList (list: int list) = 
    let (_, pairList) = List.foldBack (fun elem (pairAcc, listAcc) -> 
                                        match pairAcc with
                                        | None -> (Some(elem), listAcc)
                                        | Some(next) -> (None, (elem, next) :: listAcc))
                                        list
                                        (None, [])
    pairList

Be aware this will drop the first item in the list if the input contains an odd number of elements.

Upvotes: 1

Related Questions