〜before(l,r)是什么意思

Mor*_*ang 11 haskell pattern-matching lazy-evaluation

我读了Haskell的图书馆

partitionEithers :: [Either a b] -> ([a],[b])
partitionEithers = foldr (either left right) ([],[])
 where
  left  a ~(l, r) = (a:l, r)
  right a ~(l, r) = (l, a:r)

Run Code Online (Sandbox Code Playgroud)

~before 是什么意思(l, r)

luq*_*qui 19

这是一个懒惰的模式匹配。这意味着模式匹配被假定为成功,并且仅在需要其数据时才实际执行。

ghci> strictPat (a,b) = "hello"
ghci> lazyPat  ~(a,b) = "hello"

ghci> strictPat undefined
"*** Exception: Prelude.undefined
ghci> lazyPat undefined
"hello"

ghci> strictPat2 (a,b) = "the values are " ++ a ++ " and " ++ b
ghci> lazyPat2  ~(a,b) = "the values are " ++ a ++ " and " ++ b

ghci> strictPat2 undefined
"*** Exception: Prelude.undefined
ghci> lazyPat2 undefined
"the values are *** Exception: Prelude.undefined
Run Code Online (Sandbox Code Playgroud)

在这里使用它partitionEithers可以使它成为一个很好的流光。否则,它将必须评估整个列表,然后才能返回其结果中的任何一个的第一个元素(因为例如,left将强制由递归调用生成的传入对,将不得不强制其传入对,依此类推...)。