Defining a datatype in Haskell
Greetings, I am new to Haskell and I've gotten stuck in defining a datatype for an assignment.
I need to create the "Strategy" type, it's basically a string with 1-6 characters each representing a numeric value, and I must represent values greater than 9 as a letter (up to 35 total different values), I tried defining an auxiliary type representing each possible value and using that to create my type, but my code isn't working and I have ran out of ideas. This is the definition I have been trying:
data Value = '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'A' | 'B' |
'C' | 'D' | 'E' | 'F' | 'G' | 'I' |'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' |
'Q' |'R' | 'S' | 'T' | 'U' | 'V' | 'W' 开发者_运维百科| 'Y' | 'X' | 'Z'
data Strategy = Value | Value:Value | Value:Value:Value |
Value:Value:Value:Value | Value:Value:Value:Value:Value |
Value:Value:Value:Value:Value:Value
The Value type isn't accepting the numbers, and the Strategy type "sort of" works up to the second constructor after which it goes bust. Thanks for your help!
Just like your previous (deleted) question, this looks a lot like homework. It also helps if you pick a real name and not use this throw-away account.
This page tells you how to use haskell's data
type declarations. What are you doing different/wrong?
You use characters instead of constructors for
Value
. The'1'
'2'
, etc are all characters, you need a constructor along with zero or more fields likeValueCon1 Char
andValueCon2 String
You are using list constructors and what I assume is a field of
Value
instead of defining any new constructors forStrategy
. Perhaps you wantdata Strategy = Strat [Value]
, which will accept a list of any size. While more painful you can define many many strategy constructors with a finite number of separateValue
fields.
BTW - where is your course taught? It seems late in the term to be covering these basics.
type Strategy = [Char]
^^ how I'd actually do it.
Or, maybe
newtype Strategy = Strategy [Char]
This is less principled, as the obligation is on you to not fill it with nonsense. Using the newtype solution, you can use "smart constructors" and say, e.g.
mkStrategy :: [Char] -> Strategy
mkStrategy x
| {- list is valid -} = Strategy x
| otherwise = error "you gave me a bad strategy!"
in real code, you don't want to throw error, but return an option type, but that's another story...
精彩评论