F#分割功能

Dav*_*zov 5 recursion f# split value-restriction

我正在构建一个合并排序函数,我的split方法给了我一个值限制错误.我正在使用2个累积参数,这两个列表是由拆分产生的,我最后打包成一个元组用于返回.但是我得到了一个值限制错误,我无法弄清楚问题是什么.有没有人有任何想法?

let split lst = 
    let a = []
    let b = []
    let ctr = 0
    let rec helper (lst,l1,l2,ctr) =
        match lst with
          | [] -> [] 
          | x::xs -> if ctr%2 = 0 then helper(xs, x::l1, l2, ctr+1)
                    else 
                    helper(xs, l1, x::l2, ctr+1)
    helper (lst, a, b, ctr)
    (a,b)
Run Code Online (Sandbox Code Playgroud)

任何输入都表示赞赏.

The*_*ght 10

正如你所写的那样,代码并没有多大意义.默认情况下,F#使用不可变值,因此,您当前编写的函数可以简化为:

let split lst = 
    let a = []
    let b = []
    (a,b)
Run Code Online (Sandbox Code Playgroud)

这可能不是你想要的.事实上,由于不可变的绑定,预先定义a, b和没有任何价值ctr.

这是一个递归函数,可以解决这个问题:

let split lst = 
    let rec helper lst l1 l2 ctr =
        match lst with
        | [] -> l1, l2 // return accumulated lists
        | x::xs -> 
            if ctr%2 = 0 then 
                helper xs (x::l1) l2 (ctr+1) // prepend x to list 1 and increment
            else 
                helper xs l1 (x::l2) (ctr+1) // prepend x to list 2 and increment
    helper lst [] [] 0
Run Code Online (Sandbox Code Playgroud)

你也可以使用递归函数来解决这个问题List.fold,它fold是一个更高阶的函数,它推广了我们在上面的递归函数中明确描述的累积过程.

这种方法更简洁,但很可能不熟悉函数式编程的新手,所以我试图更详细地描述这个过程.

let split2 lst =
    /// Take a running total of each list and a index*value and return a new 
    /// pair of lists with the supplied value prepended to the correct list
    let splitFolder (l1, l2) (i, x) =
        match i % 2 = 0 with
        |true -> x :: l1, l2 // return list 1 with x prepended and list2
        |false -> l1, x :: l2 // return list 1 and list 2 with x prepended
    lst
    |> List.mapi (fun i x -> i, x) // map list of values to list of index*values
    |> List.fold (splitFolder) ([],[]) // fold over the list using the splitFolder function
Run Code Online (Sandbox Code Playgroud)

  • 对人而言,就像一个魅力.还在学习F# - 以前从未使用过函数式语言.为助攻干杯! (2认同)