Reputation: 25
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
Upvotes: 0
Views: 395
Reputation: 8467
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
Upvotes: 3