optimization - Least expensive way to construct cyclic list in Haskell -
so if want construct circular list of n 0's , 1 1, of following ways better/cheaper? , there better/cheaper way? taking account n integer , may large (though realistically not going exceed 2^32).
azerosandones :: integer -> [int] azerosandones n | n >= 0 = cycle (genericreplicate n 0 ++ [1]) | otherwise = [] versus
bzerosandones :: integer -> [int] bzerosandones n | n >= 0 = tail (cycle (1 : genericreplicate n 0)) | otherwise = []
i'd go second, because it's efficient , plenty clear enough. first depend on whether genericreplicate able fuse ++ in fashion. best way find out sure run
ghc -o2 -ddump-simpl -dsuppress-all whatever.hs | less and pore on spews.
that said, entire length of cycle allocated in memory. such nature of cycle function implemented, , not seem change (barring significant advance—foldr/build fusion not seem sufficient). better off avoiding altogether writing rest of code differently.
ah yes, thought of else. if consume list in "single-threaded" fashion, can dispense cycle altogether:
weirdthing n = genericreplicate n 0 ++ [1] ++ weirdthing n
and that's final answer. makes infinite list instead of cyclic list, when n big enough, that's better.
Comments
Post a Comment