我从列表[1..6]
中得到一个5个元素的列表,按升序排序,我必须开发两个函数:
- 检查是否存在 * 恰好 * 4个相等的元素(例如,
11112
,44445
,15555
), - 检查是否存在 * 恰好 * 3个相等元素,以及 * 恰好 * 2个相等元素(例如,
22244
、11122
)
我可以假设像numberOfOccurrences
、isPermutation
、isSorted
、maximum
和minimum
这样的函数。
numberOfOccurrences :: Eq a => a -> [a] -> Int
numberOfOccurrences _ [] = 0
numberOfOccurrences x (y:ys)
| x == y = 1 + numberOfOccurrences x ys
| otherwise = numberOfOccurrences x ys
isPermutation :: Eq a => [a] -> [a] -> Bool
isPermutation [] [] = True
isPermutation xs [] = False
isPermutation xs (y:ys) | length xs /= length (y:ys) = False
| otherwise = isPermutation (delete y xs) ys
字符串
我对第二个问题的解决方案是:
p :: [Int] -> Bool
p xs = 3 == maximum (map length (group xs))
型
但是,我应该使用函数isPermutation
和numberOfOccurrences
。关于这个问题有什么提示吗?
感谢丹尼尔瓦格纳发现我的错误。我想这是2的解。
p :: [Int] -> Bool
p xs = 3 == maximum ns && length ns == 2
where
ns = (map length (group xs))
型
然而,这不是所需的解决方案。
2条答案
按热度按时间hk8txs481#
就我个人而言,我会从超级愚蠢的事情开始。
字符串
它很容易写,很容易读,而且效率也不是特别低。
类似的策略适用于另一个。
6qqygrtg2#
虽然这不使用命名的函数,但我会开发一个行程编码,这很容易,因为我们知道元素是排序的。
字符串
现在我们只需要能够计算第二个元素为3或4的元组的数量。
型