【问题标题】:Haskell - Saving string input into a listHaskell - 将字符串输入保存到列表中
【发布时间】:2020-11-24 01:45:24
【问题描述】:

我是 Haskell 初学者,我正在为一个项目做一个小文件,该项目应该为两个人的小组输入交互数据,并将其保存到一个列表中以在最后输出。我已尽力实现这一点,但无论输入什么,程序似乎都会遇到“停止”情况。任何帮助或建议将不胜感激。

import Data.List
import Text.Read

main :: IO ()
main = do
    putStrLn "This program is a means to record interactions between individuals during the COVID-19 pandemic."
    putStrLn "Please enter your interactions in this format: 'x interacted with y'"
    inputs <- getUserInputs
    putStr "input: "
    putStrLn ("list sequence " ++ show (inputs))

parseInput :: String -> Maybe String
parseInput input = if input == "stop" then Nothing else (readMaybe input):: Maybe String

getUserInputs :: IO [String]
getUserInputs = do 
    input <- getLine
    case parseInput input of
    Nothing -> return []
    Just aString -> do
        moreinputs <- getUserInputs
        return (aString : moreinputs)

【问题讨论】:

  • readMaybe 只对带引号的字符串成功,所以如果你输入"a" 它将起作用,但不是a。您可能想删除 readMaybe 并简单地使用... else Just input

标签: list loops haskell input io


【解决方案1】:

ShowRead 旨在将值的表示形式生成和使用为 Haskell 表达式。这就是为什么当你在 String 上调用 show 时,它会产生一个 quoted 字符串:

> show "beans"
"\"beans\""

因此Read 期望字符串也被引用,因此readMaybe 总是在您的代码中返回Nothing,因为您没有提供引号:

> readMaybe "beans" :: Maybe String
Nothing

> readMaybe "\"beans\"" :: Maybe String
Just "beans"

因此修复很简单:删除对readMaybe 的调用并直接返回字符串:

parseInput1 :: String -> Maybe String
parseInput1 input = if input == "stop"
  then Nothing
  else Just input

根据风格偏好,您还可以使用警卫、模式匹配或Maybe monad 代替if

parseInput2 input
  | input == "stop" = Nothing
  | otherwise = Just input
parseInput3 "stop" = Nothing
parseInput3 input = Just input
import Control.Monad (guard)

parseInput4 input = do
  -- ‘guard’ returns ‘Nothing’,
  -- short-circuiting the ‘do’ block,
  -- if its condition is ‘False’.
  guard (input /= "stop")
  pure input

ReadShow 适用于简单的程序,尤其是在您学习 Haskell 时,但在较大的应用程序中,将它们主要用于调试输入和输出以及 reading 输入您已经验证过会很有帮助.解析库和漂亮打印库分别用于更多涉及的解析和生成人类可读的输出; megaparsecprettyprinter 是该区域中不错的默认选择。

【讨论】:

    猜你喜欢
    • 2015-05-08
    • 2017-03-11
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多