RWH 4章練習問題1
なんか作るのにすごい時間かかった・・・
- リストを述語で分割
splitWith :: (a -> Bool) -> [a] -> [[a]] splitWith f [] = [] splitWith f xs = case span f xs of (a,b) -> a : (splitWith f $ snd $ span (not . f) b)
> splitWith (/= 'a') "igaiahaidihoihihoaofha" ["ig","i","h","idihoihiho","ofh"]
- テキストの行列入れ替え
import Data.List inversionStr = unlines . transpose . fill . lines where fill xss = addBranks (maxLength xss) xss -- maxLength = foldl (\a b -> max a $ length b) 0 maxLength = maximum . map length -- addBranks n [] = [] -- addBranks n (xs:xss) = (addBrank n xs) : (addBranks n xss) addBranks n = map (addBrank n) addBrank n xs = xs ++ (brank $ n - length xs) -- brank 0 = [] -- brank n = ' ':(brank $ n - 1) brank n = take n $ repeat ' '
> putStrLn $ inversionStr "hello\nworld\naaa\nbbbbb\nccccccc\ndd\n" hwabcd eoabcd lrabc ll bc od bc c c
- おまけ
zipWithN を作ってみる。
import Data.List zipWithN f = map (foldl1 f) . transpose
> zipWithN (+) [[1,2,3],[4,5,6],[7,8,9]] [12,15,18]
transpose すげぇ。