如何用writeFile将每个[String]写入haskell中的文件?

lkn*_*dhu 4 io haskell

我怎么能用writeFile写一个[String]呢?

我有 ["one", "two", "three"]

我想进入文件:

one two three
Run Code Online (Sandbox Code Playgroud)

如何用haskell做到这一点?如果需要,我可以写一个额外的功能.

Tar*_*sch 12

我建议使用unwords :: [String] -> String而不是使用intersperse.我想简单回答一下这个简单的例子,使用ghci:

Prelude> let ss = ["one", "two", "three"]
Prelude> writeFile "myfile" $ unwords ss
Prelude> readFile "myfile"
"one two three"
Run Code Online (Sandbox Code Playgroud)


app*_*ive 10

这并不是说什么Tarrasch,prnr也没有说,但困难是因为没有将IO与纯函数分开:你说

我有["one", "two", "three"],我想把它变成一个文件:one two three.

你有一个字符串列表,并希望做一些事情,即你正在寻找一个功能lkndfhu :: [String] -> IO ().确实如此,但如果你问:

我想写一个(新)文件是什么东西?

你会注意到它与这种情况相同:

我想写什么东西到stdout?

我想要附加到文件file.txt的内容是什么?

嗯,是的"one two three" :: String.你想要的东西,映射["one", "two", "three"]"one two three",没关系,你打算用做什么"one two three"

所以你真的在寻找一个lkndfhu_pure :: [String] -> String可以组合putStrLn或者writeFile filename类型的功能String -> IO ()

那么prelude函数concat :: [String] -> String,有正确的类型,但它会产生"onetwothree",文件或stdout看起来如此:

一二三

Prelude函数unlines :: [String] -> String具有正确的类型,但会产生"一个\ntwo \nthree",文件看起来如此:

一个
2
3

[String] -> String你想要的预先给定的Prelude 功能是unwords作为Tarrasch笔记; 但由于pmr票据unwordsunlines是两种组合物concat :: [[a]] -> [a]intersperse :: a -> [a] -> [a]-基本上是:

 unwords mystrings = concat (intersperse " " mystrings)
 unlines mystrings = concat (intersperse "\n" mystrings)
Run Code Online (Sandbox Code Playgroud)

或者,等效地,

 unwords  = concat . intersperse " " 
 unlines  = concat . intersperse "\n" 
Run Code Online (Sandbox Code Playgroud)

(这些不是Prelude实际使用的定义.)作为pmr注释,它的抽象性intersperse意味着它可以IO以复杂的方式使用,但没有迹象表明这是你需要的.请注意,unwords unlines并且intersperse有类似于类似字符串的类型的变体,例如ByteStringText

如果你想在传递给IO之前考虑与使用纯函数一致的文档准备,你可能会看看Haskell平台附带的漂亮的打印库(还有很多其他的).在ghci类型中:m +Text.PrettyPrint,然后键入:browse. ghci(和Hugs)Doc以特殊方式实现类型,因此Doc如果将表达式渲染为字符串并将其写入文件,则评估表达式将显示给读者看起来如下:

 PrettyPrint> let lknfdhu_strings = ["one", "two", "three"]
 PrettyPrint> :t lknfdhu_strings
 lknfdhu_strings :: [String]
 PrettyPrint> let lknfdhu = map text lknfdhu_strings
 PrettyPrint> :t lknfdhu
 lknfdhu :: [Doc]
 PrettyPrint> hcat lknfdhu
 onetwothree
 PrettyPrint> hsep lknfdhu
 one two three
 PrettyPrint> vcat lknfdhu
 one
 two
 three
 PrettyPrint> let looksGood = hsep lknfdhu
 PrettyPrint> :t render
 render :: Doc -> String
 PrettyPrint> render looksGood
 "one two three"
 PrettyPrint> render (vcat lknfdhu)
 "one\ntwo\nthree"
 PrettyPrint> let dash =  " - " 
 PrettyPrint> let dashdoc = text dash
 PrettyPrint> dash
 " - "
 PrettyPrint> dashdoc
  - 
 PrettyPrint> hcat ( punctuate dashdoc lknfdhu )
 one - two - three
 PrettyPrint> hcat ( punctuate (text "   ") lknfdhu )
 one   two   three
 PrettyPrint> writeFile "lknfdhu.txt" (render looksGood)
Run Code Online (Sandbox Code Playgroud)

这些例子当然非常原始,请查看:browse文档中的所有疯狂函数和示例