【发布时间】:2018-05-01 11:34:58
【问题描述】:
如果元组中的任何两个值相同,我正在尝试编写一个函数,它将 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)
考虑到一个 n 元组有“n 选择 2”个可能的交集,在这种情况下,只有 10 个选项。但是想象一下这是一个 8 元组,有 28 种可能性,或者是一个 10 元组,有 45 种可能性。
必须有一种更惯用的方式来做到这一点,可能依赖于非确定性特征。
这应该怎么做?
【问题讨论】:
-
如果您需要在一个结构中存储任意数量的仅一种类型的数据,您可能希望使用某种列表,而不是元组。考虑例如
Maybe [Int]或Maybe (Vector Int)
标签: algorithm haskell non-deterministic