我有一个函数 myTest
,它对列表中的所有元素执行构造函数检查。它看起来像这样:
data MyType = Foo Int | Bar String deriving (Show, Read)
myThing :: [MyType]
myThing = [Foo 1, Foo 2, Foo 3, Bar "fail", Foo 5]
myTest :: [MyType] -> Bool
myTest list = foldl (\ acc x -> if isOfTypeFoo x then acc else False) True list
如果列表中的每个元素都是 Foo
,我希望 myTest
返回 True,但如果有一个或多个 Bar
,它返回 False。如果我运行 myTest myThing
,它应该返回 False
。
isOfTypeFoo
函数会是什么样子? (或者有更好的方法吗?)
最佳答案
您可以从为单个 MyType
编写谓词开始:
isFoo :: MyType -> Bool
isFoo (Foo _) = True
isFoo _ = False
然后您可以使用 all
将其扩展到列表:
isAllFoo :: [MyType] -> Bool
isAllFoo = all isFoo
关于haskell - 检查列表中的所有值是否具有特定的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33930175/