我对Haskell还是陌生的,我试图在列表中查找列表的长度,如果大于3,则返回true,反之亦然。 例如:
[[Bool]] -> Bool
xs = length xs >= 3
如果外部列表等于或大于3,则返回true,但是我想检查内部列表是否具有相同的参数。 另外,我知道映射长度会生成第二个列表的长度列表。
[[T,F,T],[F,F,T],[F,F]] -- output : False
[[T,F,T],[F,F,T],[T,F,F]] -- output : True
这是我期望找到的。
我希望我的问题的解释很清楚,谢谢。
答案 0 :(得分:2)
使用all
函数的可行解决方案:
check :: [[Bool]] -> Bool
check = all ((>=3) . length)
当每个元素都满足谓词时,all
函数将返回True
;在这种情况下,当列表的长度大于或等于3时,谓词(>=3) . length
的计算结果为True
。因此,如果all
的内部列表的长度大于或等于3,则check
的值为True
。
使用您提供的代码并避免使用无点样式,这可能有助于组合上述解决方案:
lengthGreaterEqualThree :: [Bool] -> Bool
lengthGreaterEqualThree xs = length xs >= 3
check' :: [[Bool]] -> Bool
check' listOfLists = all lengthGreaterEqualThree listOfLists
答案 1 :(得分:1)
这里有四个解决方案:
allLongerThanThree :: [[a]] -> Bool
allLongerThanThree [] = True
allLongerThanThree (x:xs) = (length x) >= 3 && allLongerThanThree xs
and
allLongerThanThree :: [[a]] -> Bool
allLongerThanThree = and . fmap ((>=3) . length)
allLongerThanThree :: [[a]] -> Bool
allLongerThanThree = (foldr ((&&) . (>=3) . length) True)
all
allLongerThanThree :: [[a]] -> Bool
allLongerThanThree = all ((>=3) . length)
答案 2 :(得分:0)
如果所有子列表的长度都为3或更大,则小于3的子列表列表应为空:
hasShortLists :: [[a]] -> Bool -- The contents of the inner lists doesn't matter
hasShortLists = null . filter ((<3) . length)
(这基本上是在all
上解构一个缺口;它也等效于not . any ((< 3) . length)
。)