以不必要的命令式编程方式让生活变得困难。您正在使用优美的 Haskell 语言进行编程,并且正在寻找 goto 构造!
为什么不只是import Control.Applicative (<$>) 和写
readAndChange' = writeFile "couples.txt" =<<
unlines.map (show.extractNameAndId).lines <$> readFile "deletedId.csv"
(是的,这几乎是单行代码。它采用简洁、实用的风格,并且没有被读写行的机制所打乱。尽可能多地用纯代码完成处理,只有输入和输出是 IO-基于。)
说明:
在这里,unlines.map (show.extractNameAndId).lines 处理您的输入,将其分成几行,然后使用map 将extractNameAndId 应用到每个输入,然后使用unlines 将它们重新连接在一起。
unlines.map (show.extractNameAndId).lines <$> readFile "deletedId.csv" 将读取文件并应用处理函数。 <$> 是 fmap 的令人愉悦的语法。
writeFile "couples.txt" =<< getanswer 与 getanswer >>= writeFile "couples.txt" 相同 - 得到上面的答案然后将其写入文件。
尝试写 greet xs = "hello " ++ xs 然后在 ghci 中做这些以获得乐趣
greet "Jane" -- apply your pure function purely
greet $ "Jane" -- apply it purely again
greet <$> ["Jane","Craig","Brian"] -- apply your function on something that produces three names
greet <$> Just "Jane" -- apply your function on something that might have a name
greet <$> Nothing -- apply your function on something that might have a name
greet <$> getLine -- apply your function to whatever you type in
greet <$> readFile "deletedId.csv" -- apply your function to your file
最后一个是我们如何在readAndChange 中使用<$>。如果里面有很多数据
deletedId.csv 你会错过你好,但你当然可以这样做
greet <$> readFile "deletedId.csv" >>= writeFile "hi.txt"
take 4.lines <$> readFile "hi.txt"
查看前 4 行。
所以$ 让你可以在你给它的参数上使用你的函数。 greet :: String -> String 所以如果你写greet $ person,person 必须是String 类型,而如果你写greet <$> someone,someone 可以是产生String 的任何东西 - 字符串列表,IO String,Maybe String。从技术上讲,someone :: Applicative f => f String,但您应该首先阅读类型类和 Applicative Functors。 Learn You a Haskell for Great Good 是一个极好的资源。
为了更有趣,如果你的函数有多个参数,你仍然可以使用可爱的 Applicative 样式。
insult :: String -> String -> String
insult a b = a ++ ", you're almost as ugly as " ++ b
试试
insult "Fred" "Barney"
insult "Fred" $ "Barney"
insult <$> ["Fred","Barney"] <*> ["Wilma","Betty"]
insult <$> Just "Fred" <*> Nothing
insult <$> Just "Fred" <*> Just "Wilma"
insult <$> readFile "someone.txt" <*> readFile "someoneElse.txt"
这里你在函数后面使用<$>,在它需要的参数之间使用<*>。一开始它的工作原理有点令人惊讶,但它是编写有效计算的最实用的风格。
接下来阅读有关 Applicative Functors 的内容。他们很棒。
http://learnyouahaskell.com/functors-applicative-functors-and-monoids
http://en.wikibooks.org/wiki/Haskell/Applicative_Functors