data SomeData = A Int
| B Int
| C Int
list :: [SomeData]
list = [ A 1, B 2, C 3]
wantedData = filter (?) list -- wantedData is A 1
对于上面的代码,我应该在 (?) 中输入什么函数才能获得所需的数据?
data SomeData = A Int
| B Int
| C Int
list :: [SomeData]
list = [ A 1, B 2, C 3]
wantedData = filter (?) list -- wantedData is A 1
对于上面的代码,我应该在 (?) 中输入什么函数才能获得所需的数据?
如果您只希望列表包含A
值,那么这应该作为您的谓词:
isA (A _) = True
isA _ = False
这只是模式匹配。
更接近于编写匿名函数并且不必定义新函数的能力是列表推导式。
例如,你可以说
list = [ A 1, B 2, C 3]
wantedData = [ A n | A n <- list ] -- result: [A 1]
另一种可能:
data SomeData = A Int | B Int | C Int
deriving (Show, Read, Eq)
list :: [SomeData]
list = [ A 1, B 2, C 3 ]
wantedData :: [SomeData]
wantedData = filter (== A 1) list -- wantedData is A 1
测试:
> wantedData
> [A 1]