【问题标题】:Error in pattern matching with LazyList in F#与 F# 中的 LazyList 进行模式匹配时出错
【发布时间】:2012-06-27 19:54:25
【问题描述】:

在 SO 上的this 问题之后尝试在 F# 中合并两个 LazyLists。最初是为匹配两个列表而编写的。修改后得到这个:

let rec printLazyList (l1:LazyList<int>) (l2:LazyList<int>) =
    match (l1, l2) with
        | t, s when t |> LazyList.isEmpty && s |> LazyList.isEmpty -> printfn "";
        | t , LazyList.Cons(h2,t2) when t |> LazyList.isEmpty -> printf "%d " h2 
                                                                 let a = LazyList.empty 
                                                                 printLazyList a t2
        | LazyList.Cons(h1,t1), s when s |> LazyList.isEmpty -> printf "%d " h1 
                                                                let b = LazyList.empty 
                                                                printLazyList t1 b
        | LazyList.Cons(h1,t1), LazyList.Cons(h2,t2) -> if h1 = h2 then 
                                                            printf "%d " h1 
                                                            printLazyList t1 t2 
                                                        elif h1 < h2 then 
                                                            printf "%d " h1  
                                                            printLazyList t1 l2
                                                        else 
                                                            printf "%d " h2  
                                                            printLazyList l1 t2

问题是它没有输出。没有满足任何条件(通过在模式匹配的末尾放置 |_,_ printfn "nothing matches" 来检查这一点。LazyList 中使用的 cons 与通常的 F# 列表中的 :: 有根本区别吗?因为这适用于普通列表(参见上面的链接)。

对不起,如果这又是一个非常 n00b 的问题。 FP 在这一点上看起来相当困难。

【问题讨论】:

    标签: f# pattern-matching lazy-evaluation


    【解决方案1】:

    如果您使用fsi 测试该功能,请小心,因为fsi 控制台中有很多噪音,您的眼睛可能会跳过输出行。

    这是一个完整的测试(我使用 Nil 而不是 isEmpty 进行了一些清理,并重新组织了模式匹配以提高可读性):

    #r "FSharp.PowerPack.dll"
    
    open LazyList
    
    let rec printLazyList l1 l2 =
        match l1, l2 with
        | Nil, Nil -> printfn ""
        | Nil, Cons(h2, t2) -> 
            printf "%d " h2 
            printLazyList LazyList.empty t2
        | Cons(h1, t1), Nil -> 
            printf "%d " h1 
            printLazyList t1 LazyList.empty
        | Cons(h1, t1), Cons(h2, t2) when h1 = h2 ->
            printf "%d " h1 
            printLazyList t1 t2 
        | Cons(h1, t1), Cons(h2, t2) when h1 < h2 ->
            printf "%d " h1  
            printLazyList t1 l2
        | Cons(h1, t1), Cons(h2, t2) ->
            printf "%d " h2  
            printLazyList l1 t2
    
    let x = LazyList.ofList [1; 2];;
    let y = LazyList.ofList [3; 4];;
    printLazyList x y;;
    

    【讨论】:

    • 该死。主要感谢您的清理工作,天知道我在实验室里是怎么错过的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    相关资源
    最近更新 更多