【问题标题】:F# Recursive Functions: make list items uniqueF# 递归函数:使列表项唯一
【发布时间】:2016-01-30 04:02:10
【问题描述】:
let rec isolate (l:'a list) = 
    match l with
    | [] -> []
    | x::xs ->
        if memberof(x,xs)
        then remove (x,l)
        else isolate xs

我已经创建了 memberof 和 remove 函数,唯一的问题是当第 6 行 remove(x,l) 执行时,它不会继续使用 isolate(xs) 继续搜索列表。

有没有办法说,

if x then f(x) and f(y)

?

【问题讨论】:

  • 您是否尝试使用递归实现List.distinct
  • 是的,我相信这就是我想要写的递归函数。
  • 您的问题已经解决了吗?

标签: list recursion f# tail-recursion


【解决方案1】:

当您使用 F# 不可变列表时,remove 的结果需要存储在某处:

let rec isolate (l:'a list) = 
    match l with
    | [] -> []
    | x::xs ->
        if memberof(x,xs)
        then
            let xs = remove (x,l)
            isolate xs
        else isolate xs

回答您更一般的问题:

let f _ = ()
let f' z = z

let x = true
let y = 42
let z = 3.141

if x then
    f y
    f' z |> ignore

这里需要ignore,因为在F#中没有语句,只有表达式,所以您可以将if x then f' z视为

if x then
    f' z
else
    ()

因此第一个分支也需要返回()

【讨论】:

  • 它是 (* val isolate : l:'a list -> 'a list when 'a : equal *)
【解决方案2】:

除了 CaringDev 的回答。
你可以看看这个简单的解决方案。
值得注意的是,这不是最快的方法。

let rec isolate (acc : 'a list) (l : 'a list) = 
  match l with
  | [] -> acc
  | head :: tail -> 
    if memberof (head, tail)
    then remove (head, tail) |> isolate (acc @ [head])
    else isolate (acc @ [head]) tail

let recursiveDistinct = isolate []
let uniqValues = recursiveDistinct [ 1; 1; 2; 3] //returns [1;2;3]

【讨论】:

    【解决方案3】:
    let isolate list =
        let rec isolateInner searchList commonlist =
            match searchList with
            | x::xs ->
                if (memberof commonlist x) then
                    isolateInner xs commonlist
                else
                    let commonlist = (x :: commonlist)
                    isolateInner xs commonlist
            | [] -> reverse commonlist
        isolateInner list []
    

    这是对您较大的problem 的答复的一部分。

    请注意,这不使用remove。由于您必须传递原始列表中的每个项目并且列表是不可变的,因此最好创建一个新列表并仅将唯一项目添加到新列表中,然后返回新列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 1970-01-01
      • 2014-02-26
      • 2013-03-01
      • 1970-01-01
      • 2020-02-16
      相关资源
      最近更新 更多