むずかしめのパソコン勉強の記録

計算機科学とか関数型言語とか

Haskell H99 Question 16

http://www.haskell.org/haskellwiki/99_questions/11_to_20
Haskell H99 Question 16

日本語訳

リストのN番目の要素を取り除きなさい。
Example in Haskell:

*Main> dropEvery "abcdefghik" 3
"abdeghk"

あまりコメントはないかな。
1から始めてnまでいったら飛ばしてもう一回はじめから。

dropEvery :: [x] -> Int -> [x]
dropEvery xs n = dropHelper xs n 1
    where
        dropHelper [] _ _ = []
        dropHelper (x:xs) n m
            | n == m    = dropHelper xs n 1
            | otherwise = x : dropHelper xs n (m+1)

模範解答
http://www.haskell.org/haskellwiki/99_questions/Solutions/16

面白かった模範解答。

dropEvery' :: [x] -> Int -> [x]
dropEvery' xs n = [ i | (i, k) <- (zip xs [1,2..]), (mod k n) /= 0 ]

この解答かっこいいっすねー。

zip関数は、二つのリストを引数にして、その二つをあわせたタプルのリストを返すというもの。

Prelude> :t zip

zip :: [a] -> [b] -> [(a, b)]

Prelude> zip "abcd" [1,2,3,4]

[('a',1),('b',2),('c',3),('d',4)]

タプルの2番目の要素を条件にして最終的に取り出す1番目の要素をピックアップするという形。