- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试创建一个允许用户输入字符串列表的函数。该函数获取长度并允许用户再输入 length-1 行。然后检查每条线以确保其与原始线的长度相同。但是,我遇到了一些问题,并且找不到解决方案。
问题是我可以输入超过 count-1 行,并且长度没有按照我的预期计算。例如,如果我输入 ["12","13"] 然后输入 ["121", "13"] 给出了错误,尽管它们的长度相同!
read :: IO [Line]
read = do
line <- getLine
let count = length line
lines <- replicateM (count-1) $ do
line <- getLine
if length line /= count
then fail "too long or too short"
else return line
return $ line : lines
行的类型为字符串。
readLn 给出解析错误。
最佳答案
在我看来,您对将一行作为 String
获取与将一行输入读取/解析为自定义类型之间的区别感到困惑。您正在使用getLine
,它始终返回用户键入的String
。比较:
Prelude> fmap length getLine
["12","13"]
11
Prelude> length "[\"12\",\"13\"]" -- explanation of the 11
11
Prelude> fmap length (readLn :: IO [String])
["12","13"]
2
Prelude> length ["12", "13"] -- explanation of the 2
2
如此处所示,您可能想要使用 readLn
,它首先获取一行输入,然后使用 read
解析它。
-- defined in the Prelude
readLn = do
s <- getLine
return (read s)
如果我修改您的代码以包含以下导入和定义:
import Control.Monad
type Line = [String]
...并调用 readLn
而不是 getLine
,然后我可以输入文字行 ["12","13"]
和 ["121","13"]
没有错误。
关于Haskell ReplicateM IO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9666034/
我正在尝试创建一个允许用户输入字符串列表的函数。该函数获取长度并允许用户再输入 length-1 行。然后检查每条线以确保其与原始线的长度相同。但是,我遇到了一些问题,并且找不到解决方案。 问题是我可
F# 中的 ReplicateM(Haskell)是否有等效函数? 示例: replicateM 2 [1,2,3] = [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3
我正在尝试学习如何在 Scala 中编写单子(monad)代码,但我想念 Haskell 将类型限制为属于声明函数类型的类型类的能力。 例如,我正在尝试在 Scala 中从 Control.Monad
我为一个编程问题提交的两份报告仅在一个表达式上有所不同(其中 anchors 是一个非空列表,(getIntegrals n) 是一个状态单子(monad)): Submission 1 . repl
我是一名优秀的程序员,十分优秀!