简体   繁体   中英

Comparing across data types in Haskell

Trying to figure out the best way to compare two elements that have similar values, but different types.

For example, this function should print "Yes" if the user enters "A", "B" or "C," and "No" for anything else.

data Letter = A | B | C deriving (Read, Show)
type LetterList = [Letter]

main = do
   putStrLn "Enter a capital letter, and we'll see if it's in the Letter type!"
   myLetter <- getLine
   if myLetter `elem` myLetters -- here's the rub
       then do
           print "Yes"
       else do
           print "No" 
   where
      myLetters :: LetterList
      myLetters = [A,B,C]

For your specific example, you may simply try to parse the string using reads :

case reads myLetter :: [(Letter, String)] of
    [(_, "")] -> putStrLn "yes"
    otherwise -> putStrLn "no"

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