[英]Error in pattern matching with LazyList in F#
在SO上出現此問題后,嘗試合並F#中的兩個LazyList。 最初是為了匹配兩個列表而寫的。 進行了修改以獲取此信息:
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#list?因為這適用於普通列表(請參見上面的鏈接)。
抱歉,這又是一個真正的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;;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.