We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,619 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Haskell: Data and Class problem

I am fairly new to Haskell and have been experimenting with data and class declarations. I have been trying to do this:

data Fire = Burn | Ember
data Water = Bubble | WaterGun

class Elements a

instance Elements Fire
instance Elements Water

data Elemental = Elemental { name :: String,
                             move :: (Elements a) => a
                           }

So, the idea was that "move" in the data constructor "Elemental" would be able to take any value from either the type Fire or Water. However, the error message tells me this is an illegal polymorphic type.

Therefore, I tried creating a function that could read my value for me after "show" was applied to the move. Hence, the data declaration for Elemental could now assign "move" to a String. The function looked like this:

getMove :: (Elements b) => String -> b
getMove x = read x :: (Elements  a) => a

This will not work either, as the function "read" complains of ambiguity in the letter a. I also tried this (amongst other attempts)

getMove :: (Elements b) => String -> b
getMove "Burn" = Burn
getMove "Ember" = Ember
getMove "Bubble" = Bubble
getMove "WaterGun" = WaterGun
getMove _ = error "Unknown move!"

The above caused the function to infer the type Fire, and then complain about the type Water. So, how can I either create a function that can return multiple types like I am trying to above, or is there a way to adjust the data declaration for Elemental?

Also, I have noticed that "3 :: (Num a) => a" will work but "Burn :: (Elements a) => a" causes an ambiguity error. Why is this the case?

Please help!

deathsandwich

1
Contributor
0
Replies
1
View
Question
Answered
deathsandwich
Newbie Poster
2 posts since Aug 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Question Self-Answered as of 2 Years Ago

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.5092 seconds using 2.7MB