Aru*_*iRC 1 f# pattern-matching lazy-evaluation
试图在SO上的这个问题之后合并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
Run Code Online (Sandbox Code Playgroud)
问题是它没有输出.没有满足任何条件(通过|_,_ printfn "nothing matches"在模式匹配的末尾加上一个来检查.cons在LazyList中使用的与::通常的F#列表中的基本区别是什么?因为这适用于普通列表(参见上面的链接).
对不起,如果这又是一个真正的n00b问题.FP在这一点上看起来相当困难.
如果您使用测试功能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;;
Run Code Online (Sandbox Code Playgroud)