我正试图让Haskell从文件中随机选择一行并打印出来。我的尝试如下:
import Data.Random.Extras (choice)
main :: IO ()
main = do
filecontents <- readFile "wordlist.txt"
let words = lines filecontents
let word = choice $ words
word >>= putStrLn
最后一行是发生错误的地方。>>=
期望IO String
,但是word
是Data.RVar.RVar String
。(该变量被称为"单词",因为每行应该是一个单词。)
我已经阅读了RVar的文档,但经过一些黑客攻击,我不知道如何解决我的问题。有什么想法吗?
我使用的是Haskell平台OS X 10.9安装中的ghc 7.6.3。
完整的错误如下:
[ 01:46 PM (51) integral:thoth ~/Source/pwgen ] > ghc -o pwgen pwgen.hs
[1 of 1] Compiling Main ( pwgen.hs, pwgen.o )
pwgen.hs:40:3:
Couldn't match type `Data.RVar.RVarT
Data.Functor.Identity.Identity'
with `IO'
Expected type: IO String
Actual type: Data.RVar.RVar String
In the first argument of `(>>=)', namely `word'
In a stmt of a 'do' block: word >>= putStrLn
In the expression:
do { filecontents <- readFile "wordlist.txt";
let words = lines filecontents;
let word = choice $ words;
word >>= putStrLn }
最后,我意识到有更有效的方法可以从文件中随机选择一行。我只追求最低限度的工作。我也是Haskell的初学者,可能有一些基本的误解,尤其是关于IO和monad。
您可以使用
import Data.Random
然后修改主
main = do
...
let word = sample $ choice words
putStrLn =<< word
这是因为当您导入Data.Random
时,它包含IO
的MonadRandom
实例,并使用从IO monad获得的生成器为runRVar
提供方便的包装器sample
。