首页 > 解决方案 > 如何让 `elem` 在 1-50 而不是 1-9 的列表之间检查我的输入?它拒绝任何超过个位数的东西

问题描述

    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

如何使列表为 [1..50] 而不会出现解析错误?现在我在'[value]'部分得到解析错误,因为它说预期类型Char,但实际类型是String。

标签: haskell

解决方案


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

以上内容将加载到 ghci 中,并按预期工作。重要的是 validSlot 知道它的第二个参数是一个 Int - 这样(读取值)可以推断它应该返回一个 int。我发现以下内容更容易阅读

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

在这里,由于您要返回值并且 discLocation 的类型是 Grid -> IO Int,所以 readLn 知道它应该读取一个 Int。


推荐阅读