计算列表中的元素(haskell)



这是我作业的一小部分,我必须计算列表中的元素,如果count == 2则返回true。该列表中的元素不是固定的,而是使用不同的函数进行筛选,例如allNumbers。我必须使用这个现有的函数来检查它是否有2个元素。

检查函数的定义将是:

isTrue :: Int -> Bool

我已经定义了一个当前函数

divisors :: Int -> [Int]
divisors n | n < 1 = []
           | otherwise = filter (k -> n `mod` k == 0) [1..n] 

它所做的是列出所有能除n的数字,现在我需要在同一个程序中创建另一个函数isTrue,如果上面函数产生的列表只有两个数字,则该函数将返回true

据我所知,您需要一个接受列表并返回布尔值的函数。因此,签名应该是这样的:

doit :: [a] -> Bool
doit (x:y:z) = True -- matches if the list contains at least 2 elements
doit _ = False      -- matches otherwise (i.e. list has 0 or 1 element)
-- or, we match only if the length is exactly 2
newdoit :: [a] -> Bool
newdoit [a,b] = True
newdoit _ = False
-- or even more elegant
simpledoit l = (length l)==2
-- the complete function is then e.g.
completefunc l = newdoit (divisors l)

我不想给出整个解决方案,但我认为值得指出的是,除了使用length函数计算列表长度然后产生适当结果的一些解决方案外,您还可以考虑在这里使用模式匹配,因为您与(2)比较的长度非常小。比如

hasLengthOfTwo <pattern_matching_lists_with_two_elements> = True
hasLengthOfTwo _ = False

这样做的一个小优点(可能不相关)是它也适用于无限列表

length' xs = case ((length xs) > 2) of
                  True -> True
                  _ -> False

最新更新