3要素のwindowをスライドする関数
↑タイトルの付け方が難しい
こんな挙動をする関数
code:input
1,2,3,4,5,6
code:output
1,2,3],2,3,4,3,4,5,[4,5,6
3要素のwindowをずらしていき、すべてのwindowの結果を返す
先にリストの周囲を0でpaddingすることで、各要素の隣接する要素の取得もできる
code:output
0,1,2],1,2,3,2,3,4,3,4,5,4,5,6,[5,6,0
再帰
code:hs
-- >>> windows3 1,2,3,4,5,6
-- 1,2,3],2,3,4,3,4,5,[4,5,6
windows3 :: a -> a
windows3 (a:b:c:rs) = a,b,c : windows3 (b:c:rs)
windows3 _ = []
関数の組合わせ
ここで見たのを参考にした
code:hs
-- >>> windows3 1,2,3,4,5,6
-- 1,2,3],2,3,4,3,4,5,[4,5,6
windows3 :: a -> a
windows3 = filter ((>= 3) . length) . map (take 3) . tails
tails関数を使ってる
table:雑な解説
入力 [1,2,3,4]
tailsの出力 [[1,2,3,4], [2,3,4], [3,4], [4], []]
map (take 3)の出力 [[1,2,3], [2,3,4], [3,4], [4], []]
filterの結果 [[1,2,3], [2,3,4]]
リスト内包表記
code:hs
-- >>> windows3 1,2,3,4,5,6
-- 1,2,3],2,3,4,3,4,5,[4,5,6
windows3 :: a -> a
windows3 xs = [ x, y, z | (x:y:z:_) <- tails xs ]
ちなみに、2次元リスト版
3 * 3のwindowをスライドする
code:hs
-- >>> windows33 1,2,3,4],5,6,7,8,9,10,11,12,[13,14,15,16
-- [
-- [
-- 1,2,3,5,6,7,9,10,11,
-- 2,3,4,6,7,8,10,11,12
-- ],
-- [
-- 5,6,7,9,10,11,13,14,15,
-- 6,7,8,10,11,12,14,15,16
-- ]
-- ]
windows33 :: a -> a
windows33 = map (map concat . transpose . map windows3) . windows3
-- windows33 = map (map concat . transpose . map windows3) . windows3