简体   繁体   中英

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?

  1. 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 like ValueCon1 Char and ValueCon2 String

  2. You are using list constructors and what I assume is a field of Value instead of defining any new constructors for Strategy . Perhaps you want data 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 separate Value 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, eg

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...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM