我有一个函数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
myTest
如果列表中的每个元素都是a Foo
,我想返回True ,但是如果存在一个或多个Bar
,则返回False。如果我跑步myTest myThing
,它应该返回False
。
该函数是isOfTypeFoo
什么样的?(或者有更好的方法吗?)
您可以从为单个谓词编写开始MyType
:
isFoo :: MyType -> Bool
isFoo (Foo _) = True
isFoo _ = False
然后您可以使用将其扩展到列表all
:
isAllFoo :: [MyType] -> Bool
isAllFoo = all isFoo
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句