I want to merge two functions into one.
The functions are
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
Normally, I would just copy one line into the first function en change a little bit to make the syntax correct. But here I am kinda lost how to do this
As you've already noticed, you can't just directly inline here; the reason for this is that you're pattern matching on Stone
in giveValueDice
. This pattern matching can be moved inside the right side of the list comprehension:
calculateScore :: [Dobbelsteen] -> Int
calculateScore xs = sum[if d == 'W' then 5 else digitToInt d | (Stone d) <- xs]
Another method for merging these two functions is using a where
clause, which 'merges' one function into another while keeping them distince:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.