[英]How to merge two functions into one in Haskell
我想将两个功能合并为一个。
这些功能是
data Dice = Stone Char deriving (Show, Eq)
calculateScore :: [Dobbelsteen] -> Int
calculateScore xs = sum[giveValueDice x | x <- xs]
giveValueDice :: Dice -> Int
giveValueDice (Stone d) = if d == 'W' then 5 else digitToInt d
通常,我只是将一行复制到第一个函数中,然后稍作更改以使语法正确。 但是我有点迷失了如何做到这一点
正如您已经注意到的,您不能只在此处直接内联; 这是因为您要在giveValueDice
Stone
进行模式匹配。 这种模式匹配可以在列表理解的右侧移动:
calculateScore :: [Dobbelsteen] -> Int
calculateScore xs = sum[if d == 'W' then 5 else digitToInt d | (Stone d) <- xs]
合并这两个函数的另一种方法是使用where
子句,该子句将一个函数“合并”到另一个函数中,同时保持它们的区别:
calculateScore :: [Dobbelsteen] -> Int
calculateScore xs = sum[giveValueDice x | x <- xs]
where
giveValueDice :: Dice -> Int
giveValueDice (Stone d) = if d == 'W' then 5 else digitToInt d
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.