I have the following data type:
data Users = Height Int | Age Int
I then have a list of ages:
myList = [Age 44, Age 54, Age 21, Age 34, Age 22]
Which I want to apply to this function:
myFunction :: [Users] -> [Users]
myFunction li = [x + 1 | x <- li]
However this causes the following error:
"No instance for (Num Users) arising from a use of ‘+’"
How can I make this work? Do I need to separate 'Age' from each of the values?
First, the error message tells you that you are using the (+)
function on Users
, for which it is not defined.
So you could make Users
an instance of Num
, meaning that you also need to define (-)
, (*)
, negate
,.. for Users
, which seems odd.
Maybe you need something like this:
data User = User {height :: Int, age :: Int } deriving (Show)
addToHeight :: Int -> User -> User
addToHeight x (User h a) = User (h+x) a
then use:
let users = [User 180 20, User 185 22]
fmap (addToHeight 1) users
--
to leave semantics aside:
plus :: Int -> Users -> Users
plus x (Age a) = Age (a+x)
plus x (Height h) = Height (h+x)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments