F#: integers to pair of integers

一笑奈何 提交于 2019-12-11 17:18:14

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/53207395/f-integers-to-pair-of-integers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!