Help us understand the problem. What is going on with this article?

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

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"が連続します。

oskats1987
現在C#、F#、Python、Haskell、ディープラーニングを勉強中
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした