试图找出比较两个具有相似值但不同类型的元素的最佳方法。
例如,如果用户为其他任何内容输入“A”,“B”或“C”和“否”,则此功能应打印“是”。
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]
答案 0 :(得分:3)
对于您的具体示例,您可能只是尝试使用reads
解析字符串:
case reads myLetter :: [(Letter, String)] of
[(_, "")] -> putStrLn "yes"
otherwise -> putStrLn "no"