【问题标题】:Haskell: read a text file of doubles and assign a list containing them to a list variableHaskell:读取双精度文本文件并将包含它们的列表分配给列表变量
【发布时间】:2018-06-28 22:56:35
【问题描述】:

好的,我是来自 Python 的 Haskell 社区的新手,这让我发疯了。

我有一个类似于以下内容的文本文件: “1.2 1.423 2.43 英寸。

我想读取这个文本文件并将其作为双精度列表存储在 list_var 中。所以 list_var = [1.2,1.423,2.43]。这个 list_var 将在程序中进一步使用。

我似乎没有找到关于如何做到这一点的答案,大多数答案都可以打印出 list_var,例如Haskell - Read a file containing numbers into a list 但我需要更进一步的 list_var!

我试过了:

get_coefficients :: String -> [Double]
get_coefficients file_1 = do
 coefficients_fromfile <- readLines "test2.txt"
 let coefficients = map readDouble coefficients_fromfile
 return coefficients

这不起作用,readLines是

readLines :: FilePath -> IO [String]
readLines = fmap lines . readFile

而 readDouble 是

readDouble :: String -> Double
readDouble = read

提前致谢!

【问题讨论】:

  • 您不能在非 IO 函数中进行 IO 操作。您应该在 main 函数中执行 readLines,并将结果传递给 get_coefficients,这就是您链接的答案的作用。

标签: haskell io monads


【解决方案1】:

由于您使用return,因此您的输出在一个单子中,在本例中为IO 单子。正如错误消息告诉你的那样,你应该改变这一行:

get_coefficients :: String -> [Double]

到这里:

get_coefficients :: String -> IO [Double]

这是因为 Haskell 的一个核心原则:引用透明性。

如果你想使用生成的[Double],你仍然必须将它保存在IO monad 中,如下所示:

main :: IO ()
main = do
    -- This can be thought of as taking out values from the monad,
    -- but requires the promise that it'll be put back into a monad later.
    doubles <- get_coefficients "This argument does nothing, why?"
    -- This prints the list of doubles. Note: it returns an IO (),
    -- thus fufills the promise!
    -- print :: Show a => a -> IO ()
    print doubles

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    相关资源
    最近更新 更多