确定代数数据结构的类型

时间:2018-10-20 01:13:58

标签: haskell functional-programming algebraic-data-types

假设data MyAlgebraicType :: Foo Int | Bar Int。如果我的变量类型为MyAlgebraicType,如何确定它是Foo Int还是Bar Int

2 个答案:

答案 0 :(得分:3)

使用case

let var = Bar 42 in
case var of
    Foo _ -> putStrLn "It's a Foo!"
    Bar _ -> putStrLn "It's a Bar!"

可以将_替换为变量名以绑定其中包含的Int

您还可以使用模式匹配定义(比case更常见):

tellMeIt :: MyAlgebraicType -> IO ()
tellMeIt (Foo _) = putStrLn "It's a Foo!"
tellMeIt (Bar _) = putStrLn "It's a Bar!"

答案 1 :(得分:0)

模式匹配通常更好,但是在某些情况下,使用以下函数可以更容易阅读代码:

isFoo :: MyAlgebraicType -> Bool
isFoo (Foo _) = True
isFoo _       = False

isBar :: MyAlgebraicType -> Bool
isBar (Bar _) = True
isBar _       = False