concatMap

「ふつうのHaskellプログラミング」P71


●concatMap は concat と map をくっつけたもの。
Prelude> :t concat
concat :: [ [ a ] ] -> [a]
Prelude> concat [ [1,2,3],[4,5,6 ] ]
[1,2,3,4,5,6]
Prelude> concat [ [ 'a','b','c' ], [ 'd','e','f' ] ]
"abcdef"
Prelude> concat ["abc", [ 'd','e','f' ] ]
"abcdef"
Prelude> "abc"==['a','b','c']
True
Prelude> "abc"==['a','b','d']
False

{- (a -> [b]) はリストに適用させる関数って意味かな。-}
Prelude> :t concatMap
concatMap :: (a -> [b]) -> [a] -> [b]

Prelude> let expandTab c = if c == '\t' then " " else [c]
Prelude> expandTab 'a'
"a"
Prelude> expandTab '\t'
" "
Prelude> concatMap expandTab "abc\tdef"
"abc def"
Prelude> concatMap expandTab "abc\tde\tfg"
"abc de fg"

Prelude> :t expandTab
expandTab :: Char -> [Char]
Prelude> :t concatMap
concatMap :: (a -> [b]) -> [a] -> [b]

自分で定義しても同じ。


Prelude> let cmp f xs = concat $ map f xs
Prelude> cmp expandTab "abc\tde\tfg"
"abc de fg"
Prelude> :t cmp
cmp :: (a1 -> [a]) -> [a1] -> [a]