Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

haskell - How can I make `elem` check my input between a list of 1-50 rather than 1-9? It rejects anything more than single digits

    discLocation :: Grid -> IO Int

    discLocation grid = do
  
    putStrLn "Enter number from the grid "
 
    value <- getLine
  
    if value `elem` [1..50] && validSlot grid (read [value])
 
    then return  $ (read [value])
  
    else discLocation grid

How can I make it so that the list is [1..50] without getting a parse error? Now I get the parse error on the '[value]' part as it says expected type Char but actual type is String.

question from:https://stackoverflow.com/questions/65650044/how-can-i-make-elem-check-my-input-between-a-list-of-1-50-rather-than-1-9-it

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
discLocation :: Int -> IO Int

discLocation grid = do
  putStrLn "Enter number from the grid "
  value <- getLine
  if read value `elem` [1..50] && validSlot grid (read value)
    then return  $ read value
    else discLocation grid

validSlot :: Int -> Int -> Bool
validSlot _ _ = True

The above will load in ghci and it works as expected. It is important that validSlot knows that its second argument is an Int - so that (read value) can infer that it should return an int. I find the following a bit easier to read

discLocation grid = do
  putStrLn "Enter number from the grid "
  value <- readLn
  if value `elem` [1..50] && validSlot grid value
    then return value
    else discLocation grid

Here since you are returning value and discLocation is of type Grid -> IO Int, readLn knows that it should read an Int.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...