Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...