3
3

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.

はじめてのElm その1

Posted at

公式

オンラインエディタで色々試しながら遊べる。

最終的にHtmlとJSに落ちるっぽいけど、文法はHaskellライクでかなーりとっつきにくい。なので、ExampleとLearnで遊んだ結果をメモとして残していこうと思います。

ListとRecord

この中のBeginner Classesが動画で一番とっつきやすかったので、その中のList and Recordsについて

動画の内容

データ構造としてListとRecord(Hashライクな構造体)を用意し、主にリストに対して再帰的に処理をかける関数を作り、それらの部品をmapを使うことによってさらに複雑なデータの操作が出来るところまで。

List

普通に書く

list = [1,2,3,4,5]

:: を使って値を追加できる(:: : a -> [a] -> [a])

list = 1 :: 2 :: 3 :: 4 :: [] //[1,2,3,4]と等価

合計値を返すsum関数を作る

sum numbers =
  case numbers of
    [] -> 0
    hd :: tl -> hd + sum tl

caseはちゃんとインデント取らないと動かない!

ついでに長さを返すlengthも

length numbers =
  case numbers of
    [] -> 0
    hd :: tl -> 1 + length tl

これで平均値を返す関数も作れる

average numbers =
  sum numbers / length numbers

Record

名前と点数のリストを持つ生徒Recordを作る

evan = { name = "Evan", grades = [90, 85, 30, 100] }
tom = { name = "Tom", grades = [70, 65, 10, 90] }

recordの要素はドットアクセス可能

evan.name // "Evan"
tom.grades //[70, 65, 10, 90]

生徒を複数持つ先生Recordを作る

snape = { name = "Snape", students = [evan,tom] }

生徒を受け取り、平均点を返す関数を定義

averageGrade student = average student.grades

クラスの平均点をmapを使って出す

classAverage teacher = 
  average (map averageGrade teacher.students)

mapは良くある定義

map sqrt [1,4,9] // [1,2,3]

関数とコレクションを受け取り、関数を各要素に適用した結果のコレクションを返す(List.map以外にもたくさんあった。)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?