3

递归函数:

let rec listMerge (l1 : 'a list) (l2 : 'a list) =
    if l1.IsEmpty then      l2 
    elif l2.IsEmpty then    l1 
    else                    l1.Head :: l2.Head :: listMerge l1.Tail l2.Tail

现在,除非我很高兴地弄错了,否则这实际上并没有执行尾调用,如果不考虑这::是正确的关联,它可能看起来像它。

然后,我的印象(从我读过的东西,但现在找不到)通过使用额外的fun东西可以很容易地转换为尾递归。

那么,有可能吗?代码?

我的回答:所以,这就是我更改功能的方式,感谢以下答案:

let listMerge l1 l2 =
    let rec mergeLoop  (l1 : 'a list) (l2 : 'a list) acc =
        if l1.IsEmpty then      (List.rev acc) @ l2 
        elif l2.IsEmpty then    (List.rev acc) @ l1
        else                    mergeLoop l1.Tail l2.Tail (l2.Head :: l1.Head :: acc)
    mergeLoop l1 l2 []
4

5 回答 5

14

正如@Ramon 建议的那样,您应该使用模式匹配以获得更好的可读性:

let rec listMerge xs ys =
    match xs, ys with
    | [], _ -> ys
    | _, [] -> xs
    | x::xs', y::ys' -> x::y::listMerge xs' ys'

如您所见,两个 cons 构造函数(::)是最后的操作,listMerge因此该函数不是尾递归的。

您可以使用累加器以尾递归方式获取结果:

let listMerge xs ys =
    let rec loop xs ys acc =
        match xs, ys with
        | [], zs | zs, [] -> (List.rev zs)@acc
        | x::xs', y::ys' -> loop xs' ys' (y::x::acc)
    List.rev (loop xs ys [])

在上面的函数中,List.rev如果您添加更多模式来解构两个列表,直到它们都为空,则可以避免第一次调用。

在 F# 中,有一种使用序列表达式的尾递归方法,它遵循延续传递风格

let listMerge xs ys =
    let rec loop xs ys =
        seq {
            match xs, ys with
            | [], zs | zs, [] -> yield! zs
            | x::xs', y::ys' -> 
                yield x
                yield y
                yield! loop xs' ys'
        }
    loop xs ys |> Seq.toList

我喜欢这种方法,因为它方便且接近您的原始配方。

于 2012-10-31T09:15:36.960 回答
2

可以在后续调用中将构造的结果累加listMerge,最后返回累加的结果。我的 F# 技能相当生疏,但这里有一个简单的 Lisp 函数。

(defun list-merge (xs ys &optional acc)
  (cond ((< 0 (length xs)) (list-merge (rest xs) ys (cons (first xs) acc)))
        ((< 0 (length ys)) (list-merge xs (rest ys) (cons (first ys) acc)))
        (t acc)))

(list-merge '(1 2 3) '(3 4 5)) ;=> (5 4 3 3 2 1)
(list-merge '() '(1 2))        ;=> (2 1)
(list-merge '() '())           ;=> nil
于 2012-10-31T09:00:18.697 回答
1

使用累加器的简单版本:

let rec listMerge (l1 : 'a list) (l2 : 'a list) acc =
    if l1.IsEmpty then      (List.rev l2)@acc 
    elif l2.IsEmpty then    (List.rev l1)@acc
    else                    listMerge l1.Tail l2.Tail (l1.Head :: l2.Head :: acc)

我用两百万个元素列表对此进行了测试,并且没有堆栈溢出,所以我有理由相信这是尾递归。

于 2012-10-31T09:16:20.740 回答
0

我认为您必须重用在F# PowerPack中找到的原始 F# 代码。
实际上,您需要的是List.fold2,如果列表大小不同,该函数不应该抛出异常SR.listsHadDifferentLengths,而是处理较长列表的其余部分,如下所示:

let l1 = ["A1"; "A2"; "A3"; "A4"; "A5"; "A6"; "A7"]
let l2 = ["B1"; "B2"; "B3"; "B4"]

let expectedResult = ["A1"; "B1"; "A2"; "B2"; "A3"; "B3"; "A4"; "B4"; "A5"; "A6"; "A7"]

我们是这样做的:

[<CompiledName("Fold2Tail")>]
let fold2Tail<'T1,'T2,'State> f g1 g2 (acc:'State) (list1:list<'T1>) (list2:list<'T2>) = 
    let f  = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(f)
    let g1 = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(g1)
    let g2 = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(g2)
    let rec loop acc list1 list2 =
        match list1, list2 with 
        | [], [] -> acc
        | _,  []  -> g1.Invoke(acc, list1)
        | [], _   -> g2.Invoke(acc, list2)
        | (h1::t1),(h2::t2) -> loop (f.Invoke(acc,h1,h2)) t1 t2
    loop acc list1 list2

g1and是andg2类型的谓词,相应地。他们告诉如何处理两个列表的其余部分。请注意,其中有两个,因为在一般情况下和是不同的类型。是的,这有点开销,但您可以轻松地将其减少到您的需要,牺牲通用性。'State -> 'T1 list -> 'State'State -> 'T2 list -> 'State'T1'T2

用法:

let ret =
    fold2Tail
        (fun s x y  -> [ yield! s; yield x; yield y ] ) // f
        List.append // g1
        List.append // g2
        []          // 'State
        l1 l2
于 2012-10-31T12:52:02.507 回答
0

您应该使用模式匹配:

let rec merge xs ys =
  match xs, ys with
  | [], xs | xs, [] -> xs
  | x::xs, y::ys -> x::y::merge xs ys

要获得尾调用,您可以使用累加器:

let merge xs ys =
  let rec loop xys xs ys =
    match xs, ys with
    | [], xs | xs, [] -> List.fold (fun xs x -> x::xs) xs xys
    | x::xs, y::ys -> loop (y::x::xys) xs ys
  loop [] xs ys

或延续传球风格:

let merge xs ys =
  let rec loop xs ys k =
    match xs, ys with
    | [], xs | xs, [] -> k xs
    | x::xs, y::ys -> loop xs ys (fun xys -> k(x::y::xys))
  loop xs ys id
于 2012-11-04T13:18:20.487 回答