首页 > 解决方案 > (l, r)之前的~是什么意思

问题描述

我读了 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)

标签: haskellpattern-matchinglazy-evaluation

解决方案


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

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会强制传入对,这是由递归调用生成的,这将不得不强制其传入对,等等...)。


推荐阅读