haskell - 如何让 `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。
解决方案
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。
推荐阅读
- c++ - 简单的 C++ 循环占用整个 RAM
- javascript - WebRTC - 如何将 MediaStream 添加到现有的 RTCPeerConnection(没有附加任何 MediaStream)
- package - 跨 Swift 包共享 Package.swift 配置
- excel - Excel 公式问题 比较部分字段
- javascript - Javascript Debounce 没有从 vue 组件中清除它的队列
- php - 如何使用 get 将 2 个变量发送到第二个 PHP 页面
- python - 如何使用多线程加速 Python 导入?
- google-colaboratory - 如何从命令行关闭 google colab?
- android - 创建一个弹出列表来填充一个textView
- mql4 - Mql4编码我要添加试用