LoginSignup
4
4

More than 5 years have passed since last update.

[JavaプログラマのためのHaskell]四日目・高階関数の話

Last updated at Posted at 2016-01-16

前回の続き.

せっかく前回型についてやったので、今回からは関数の型の宣言をしていきます.
関数の型

第一引数の型 -> 第二引数の型 ->...->返り値の型

高階関数

他の関数を引数に取る関数のこと. ※例 map関数.

maptest.hs
main = print $ map square [1, 2, 3] -- 出力: [1, 4, 9]

square n = n * n

  ・map関数: リストの各要素に引数の関数を適用する.
         上記の例の式の値は[(square 1), (square 2), (square 3)]となり、
         すなわち[1, 4, 9]となる.

expand.hsその1

タブ文字を文字@に置換する.

expand.hs
main = do cs <- getContents
          putStr $ expand cs

expand :: String -> String
expand cs = map translate cs

translate :: Char -> Char
translate c = if c == '\t'
                then `@` 
                else c

  ・if式: 条件式の値がTrueなら式1、Falseなら式2を返す. elseは省略できない.

if 条件式 then 式1 else 式2

  ・==演算子: x == yとした場合、xとyが等しい時にTrue、等しくない時にFalseを返す.

(==) :: a -> a -> Bool

expand.hsその2

タブ文字を空白8文字に展開する.

expand.hs
main = do cs getContents
          putStr $ expand cs

expand :: String -> String
expand cs = concat $ map expandTab cs

expandTab :: Char -> String
expandTab c = if c == '\t' 
                then "        "
                else [c]

  ・concat関数: リストxsを連結して1つのリストにする.

concat :: [[a]] -> [a]
concat [[1, 2], [3], [4, 5]] → [1, 2, 3, 4, 5]
concat ["ab", "c", "de"] → "abcde"

今回はここまで!
第三回
第五回

出典
青木峰郎.ふつうのHaskellプログラミング ふつうのプログラマのための関数型言語入門.ソフトバンク クリエイティブ株式会社,2006,372p.

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4