1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

すごいH本読んだからまとめ 8 「ラムダ式」

Posted at

はじめに

ラムダ式

そもそもラムダ式とは

  • 一回だけ使用する関数を作りたいときに使う
  • 別名は無名関数
  • (\ <引数> -> <式>)で定義できる
  • 定義の先頭の\λにみえるんじゃないかなーと思う
-- mapで与える引数にラムダ式を使ってみる
*Main Lib> map (\x -> x * 3 + 5) [1,2,3,4,5]
[8,11,14,17,20]

*Main Lib> map (\xs -> length xs < 3) ["aiueo", "aiu", "ai", "a"]
[False,False,True,True]

*Main Lib> map (\xs -> head xs) ["aiueo", "aiu", "ai", "a"]
"aaaa"
  • カリー化を表現するような書き方もできる
-- 引数を一部与えると「残りの引数を与えたときに全体の値を返す関数」を返す関数を定義
*Main Lib> (\x -> \y -> \z -> x * y * z) 3 2 1
6
*Main Lib> multiple6 = (\x -> \y -> \z -> x * y * z) 3 2
*Main Lib> multiple6 7
42

-- flip関数を自分で定義するときはこの書き方が便利
flip' :: (a -> b -> c) -> b -> a -> c  
flip' f = \x y -> f y x 

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?