通过以不必要的命令方式进行编程,您使生活变得困难。您正在使用美丽的 Haskell 语言进行编程,并且正在寻找一种goto
构造!
为什么不只是import Control.Applicative (<$>)
写
readAndChange' = writeFile "couples.txt" =<<
unlines.map (show.extractNameAndId).lines <$> readFile "deletedId.csv"
(是的,这几乎是单行的。它采用简洁、实用的风格,并且没有被读写行的机制所打乱。处理过程尽可能地用纯代码完成,只有输入和输出是基于 IO 的。)
解释:
这里unlines.map (show.extractNameAndId).lines
通过将输入切割成行来处理您的输入,extractNameAndId
然后使用 应用show
到每个输入,然后使用map
将它们重新连接在一起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
, theperson
必须是 type String
,而如果你写greet <$> someone
, thesomeone
可以是任何产生 a String
-a 字符串列表,an IO String
, a 的东西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