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

时间:2019-07-30 18:54:57

标签: 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)

~之前的(l, r)是什么意思?

1 个答案:

答案 0 :(得分:19)

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

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

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