LoginSignup
3
0

More than 3 years have passed since last update.

Haskellのmap関数を使ってみた(はじめての投稿)

Posted at

Haskellで、map関数使ってみました。

まだまだHaskellのことはよく分からないですが、解説書を読みながら簡単なプログラムを作り動かしてみました。

test.hs
sa 1 = "one"
sa 2 = "two"
sa n = "other"

main::IO()
main = do
    let l=[1,2 .. 20]

    print (map sa l)

実行結果は

["one","two","other","other","other","other","other","other","other","other","other","other","other","other","other","other","other","other","other","other"]

となります。


解説

まずは最初の部分。

test.hs
sa 1 = "one"
sa 2 = "two"
sa n = "other"

関数saを定義しています。
引数に1が渡されればoneを返します。
2ならtwoを、それ以外ならotherを返します。

test.hs
    let l=[1,2 .. 20]

    print (map sa l)

main関数の中身です。
上の行は1から20までの整数のリストを表しています。
そのリストをlに束縛しています。

map関数は、関数とリストを引数に取り、リストの各要素を関数に適用します。
map sa l
つまり、リストlの最初の要素は1で、
sa 1
を実行します。
次は2なので
sa 2
を実行します。
これをリストの最後、20まで繰り返します。

よって実行結果は、
"one","two"の後が"other"が連続します。

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