F#:整数到整数对 [英] F#: integers to pair of integers

查看:93
本文介绍了F#:整数到整数对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,该函数将一个整数列表作为参数,并返回一个成对的列表作为结果.例如,[1;2;3;4]应该返回为[(1, 2); (3, 4)]

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

现在,我想使用foldBack函数但不使用索引来做到这一点.谁能给我一个关于如何制作的想法?

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 ?

任何帮助将不胜感激.

推荐答案

为什么要使用折返?

一个简单的递归函数

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

或者是尾递归的:

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

这篇关于F#:整数到整数对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆