大多数Haskell教程都教授IO使用do-notation.
我也开始使用do-notation,但这使得我的代码看起来更像是一种命令式语言而不是FP语言.
本周我看到一个教程使用IO <$>
stringAnalyzer <$> readFile "testfile.txt"
Run Code Online (Sandbox Code Playgroud)
而不是使用 do
main = do
strFile <- readFile "testfile.txt"
let analysisResult = stringAnalyzer strFile
return analysisResult
Run Code Online (Sandbox Code Playgroud)
并且日志分析工具没有完成do
.
所以我的问题是" 在任何情况下我们都应该避免使用记号吗? ".
我知道do
在某些情况下可能会使代码变得更好.
另外,为什么大多数教程都教IO do
?
在我看来<$>
,<*>
使代码更多FP比IO.
我试图通过haskell读取一个大的csv文件,并按每列生成单词count.
这个文件中有超过4M的行.
所以我选择读取一个块并每次获得字数(每行5k行).而不是总结它.
当我用12000行和120000行测试函数时,时间增加几乎是线性的.但是当读取180000行时,运行时间超过四次.
我认为这是因为内存不够,与磁盘交换使功能慢得多.
我把我的代码编写为map/reduce风格,但是如何让haskell不能将所有数据保存在内存中?
打击是我的代码和分析结果.
import Data.Ord
import Text.CSV.Lazy.String
import Data.List
import System.IO
import Data.Function (on)
import System.Environment
splitLength = 5000
mySplit' [] = []
mySplit' xs = [x] ++ mySplit' t
where
x = take splitLength xs
t = drop splitLength xs
getBlockCount::Ord a => [[a]] -> [[(a,Int)]]
getBlockCount t = map
(map (\x -> ((head x),length x))) $
map group $ map sort $ transpose t
foldData::Ord a=> [(a,Int)]->[(a,Int)]->[(a,Int)]
foldData lxs rxs = map combind wlist …
Run Code Online (Sandbox Code Playgroud) 我正在做Typeclassopedia的练习; 在Applicative
节中,我写ZipList
的pure
功能,并检查它是否遵循Applicative
法律.
我检查过:
但是当我试图检查"同态"定律时,我发现GHCi没有得到结果MZipList
.
我想这是因为我错过了指定pure
我的Applicative
类型课程.如何立即运行pure
没有<*>
它的功能Applicative
?
这是MZipList
定义和类实例:
newtype MZipList a = MZipList { getZipList :: [a] }
deriving (Show)
instance Functor MZipList where
fmap gs x = pure gs <*> x
instance Applicative MZipList where
pure a= MZipList (repeat a)
(MZipList gs) <*> (MZipList xs) = MZipList (zipWith ($) gs xs)
Run Code Online (Sandbox Code Playgroud)
当我检查"交换"法时,例如:
*Main> (MZipList …
Run Code Online (Sandbox Code Playgroud)