top page > computer > haskell > web_lecture > for_programmer > splitat_foldr.html
更新日:
文責: 重城良国

関数foldrで関数splitAtを定義

splitAtF :: Int -> [a] -> ([a], [a])

定義

step x f n | n > 0 = (x : t, d) where (t, d) = f (n - 1)
step x f _ = ([], x : d) where (_, d) = f 0

fsplitAt :: [a] -> Int -> ([a], [a])
fsplitAt (x : xs) n = step x (splitAt xs) n
fsplitAt _ _ = ([], [])

同様に展開する。

fsplitAt (x : xs) n | n > 0 = (x : t, d)
where (t, d) = fsplitAt xs (n - 1)
fsplitAt (x : xs) _ = ([], x : d)
where (_, d) = fsplitAt xs 0
fsplitAt _ _ = ([], [])

仮引数nを消す。

fsplitAt (x : xs) = step x (splitAt xs)
fsplitAt _ = const ([], [])

関数foldrで定義する。

splitAtF = flip $ foldr s (const ([], []))
where
s x f n | n > 0 = (x : t, d) where (t, d) = f (n - 1)
s x f _ = ([], x : d) where (_, d) = f 0

「関数foldrで関数dropを定義」へもどる 「関数foldrで関数dropWhileを定義」へ

正当なCSSです! HTML5 Powered with CSS3 / styling, and Semantics