简体   繁体   English

Haskell 中 forM 的返回值

[英]Return value of forM in Haskell

If I have a list input = ["1", "-2", "14", "3"] with length n and I want to convert it into an Int list, what is the return value of如果我有一个长度为n的列表input = ["1", "-2", "14", "3"]并且我想将其转换为Int列表,那么返回值是多少

forM [0..(n-1)] $ \i -> do
        let t = read (input!!(i)) :: Int 
        return ()

I figured out that t will contain the Int value of each string from the input list but I don't understand how should I put them in a new list.我发现t将包含input列表中每个字符串的Int值,但我不明白我应该如何将它们放入新列表中。 Note that this forM syntax is not written by me.请注意,这个forM语法不是我写的。 I researched how I should work with monads but I still don't really get it since I couldn't find a single example.我研究了我应该如何使用 monad,但我仍然没有真正理解它,因为我找不到一个例子。

If I have a list input = ["1", "-2", "14", "3"] with length n and I want to convert it into an Int list.如果我有一个长度为 n 的列表input = ["1", "-2", "14", "3"]并且我想将它转换为一个Int列表。

Then you should use:那么你应该使用:

map read input :: [Int]

Indeed:的确:

Prelude> input = ["1", "-2", "14", "3"]
Prelude> map read input :: [Int]
[1,-2,14,3]

I figured out that t will contain the Int value of each string from the input list but I don't understand how should I put them in a new list.我发现 t 将包含输入列表中每个字符串的 Int 值,但我不明白我应该如何将它们放入新列表中。

Variables in (pure) functional languages, like Haskell, are immutable . (纯)函数式语言(如 Haskell)中的变量是不可变的 That means that once a variable is set to a value, you can not set it to a different value.这意味着一旦将变量设置为一个值,就不能将其设置为不同的值。

In fact in Haskell, one seldomly use looping mechanisms like forM , etc. The M suffix usually says you are working with M onads, but here you do not need monads at all.事实上,在 Haskell 中,很少使用像forM等的循环机制。 M后缀通常表示您正在使用M onads,但在这里您根本不需要 monads。 I strongly advice not to use do , etc. before you have some basic understanding on how a monad works.我强烈建议在您对 monad 的工作原理有一些基本了解之前不要使用do等。 See for example the A fistful of Monads chapter on Learn You A Haskell [lyah] .例如,参见Learn You A Haskell [lyah]A fistful of Monads章节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM