The*_*ist 3 algorithm haskell non-deterministic
我正在尝试编写一个函数,如果元组中的任何两个值相同,它将Nothing
成为Just
Int
元组.对于五个值的元组,这就是我所拥有的.显然,还有改进的余地:
nothingIfMatch :: Maybe (Int, Int, Int, Int, Int) -> Maybe (Int, Int, Int, Int, Int)
nothingIfMatch Nothing = Nothing
nothingIfMatch (Just (a, b, c, d, e))
| a == b = Nothing
| a == c = Nothing
| a == d = Nothing
| a == e = Nothing
| b == c = Nothing
| b == d = Nothing
| b == e = Nothing
| c == d = Nothing
| c == e = Nothing
| d == e = Nothing
| otherwise = Just (a, b, c, d, e)
Run Code Online (Sandbox Code Playgroud)
考虑到n元组有"n选2"可能的交叉点,在这种情况下,只有10个选项.但想象一下,这是一个8元组,有28种可能性,或者10元组,有45种.
必须有更惯用的方法来做到这一点,可能依赖于非确定性特征.
该怎么做?
我们可以先生成一个Int
s 列表,然后执行所有相等检查:
import Data.List(tails)
twoEqual :: Eq a => [a] -> Bool
twoEqual xs = any (uncurry elem) [(h, t) | (h:t) <- tails xs]
Run Code Online (Sandbox Code Playgroud)
这里我们首先为列表中的每个元素生成一个元组,其中包含元素和列表的其余部分.然后我们执行elem
函数:我们调用elem
项目和列表的其余部分,如果any
这些检查成立,那么我们返回True
,False
否则.
所以现在我们可以从这个元组构造一个列表,然后使用一个guard来执行检查:
nothingIfMatch :: Eq a => Maybe (a, a, a, a, a) -> Maybe (a, a, a, a, a)
nothingIfMatch = (>>= f)
where f r@(a, b, c, d, e) | twoEqual [a, b, c, d, e] = Nothing
| otherwise = Just r
Run Code Online (Sandbox Code Playgroud)
我们可以轻松地向元组添加一个额外的元素,并将其添加到twoEqual
调用中的列表中.在这里,我们仍然执行O(n 2).如果我们可以先对元素进行排序,我们可以在O(n log n)中进行,或者我们甚至可以在O(n)中进行,以防元素可以清洗并且不会发生散列冲突.
例如:
-- O(n log n) if the elements can be ordered
import Data.List(sort, tails)
twoEqual :: Ord a => [a] -> Bool
twoEqual xs = or [h1 == h2 | (h1:h2:_) <- tails (sort xs)]
Run Code Online (Sandbox Code Playgroud)
或者在元素可以散列的情况下:
-- O(n) in case the elements are hashable and no hash collisions
import Data.Hashable(Hashable)
import Data.HashSet(fromList, member)
twoEqual :: (Hashable a, Ord a) => [a] -> Bool
twoEqual xs = any (flip member hs) xs
where hs = fromList xs
Run Code Online (Sandbox Code Playgroud)