在Haskell中匹配多态数据

Jos*_*iro 3 haskell

假设我们有一个名为Stuff的数据:

data Stuff = Stuff1 Int
           | Stuff2 Int
           | Stuff3 Int

sumStuff :: [Stuff] -> Int
sumStuff [] = 0
sumStuff ((Stuff1 x):xs) = x + sumStuff xs
sumStuff ((Stuff2 x):xs) = x + sumStuff xs
sumStuff ((Stuff3 x):xs) = x + sumStuff xs

sumStuff' :: [Stuff] -> Int
sumStuff' [] = 0
sumStuff' ((_ x):xs) = x+sumStuff xs
Run Code Online (Sandbox Code Playgroud)

如何在没有模式匹配的情况下匹配所有类型,如sumStuff'中的错误定义?

先感谢您!

bhe*_*ilr 13

如果它与您的示例一样同质,您可以对数据结构采取不同的方法:

data StuffType = Stuff1 | Stuff2 | Stuff3 deriving (Eq, Show)

data Stuff a = Stuff StuffType a deriving (Eq, Show)

extractStuff :: Stuff a -> a
extractStuff (Stuff _ a) = a

sumStuff :: Stuff Int -> Int
sumStuff = sum . map extractStuff
Run Code Online (Sandbox Code Playgroud)

我甚Stuff至将多态的值包含在内,以防你想在其中存储Strings甚至更多Stuffs.这种方法允许您StuffType在需要时进行模式匹配,但如果不需要,可以使用单个模式案例.

您还可以使用记录来定义它,以避免模式匹配:

data Stuff a = Stuff { stuffType :: StuffType, extractStuff :: a } deriving (Eq, Show)
Run Code Online (Sandbox Code Playgroud)

并且sumStuff具有相同的定义,但您不需要extractStuff手动定义.