Elm文法メモ
Elmの文法メモ。適当に追加していく予定。
値
特に変なリテラルはない気がする。
import Graphics.Element exposing(show) -- 文字 exclamation = '!' -- 文字列 hello = "hello" -- 文字列の連結 hw = hello ++ "world" -- 数値 num = 2 + 3 * 4 -- 除算(float) floatNum = 3/2 -- 除算(Int) intNum = 3//2 main = show (hw, num, floatNum, intNum)
関数
こんなかんじ。
import Graphics.Element exposing(show) isNegatice n = n < 0 main = show (isNegatice 3)
ちなみにこう書くとエラーになる。
main = show isNegatice 3
【stdout】
Error in test2.elm: Type mismatch between the following types on line 6, column 3 to 7: Graphics.Element.Element a -> b It is related to the following expression: show
括弧を無くしたい場合はこう。
import Graphics.Element exposing(show) isNegatice n = n < 0 main = isNegatice 3 |> show
これでエラー出ない。
その他、型注釈とか。
import Graphics.Element exposing(show) -- 2引数関数 add a b = a + b -- 型アノテーション sub : Int -> Int -> Int sub x y = x - y main = sub 10 5 |> add 3 |> show
if式
if式は3項演算子的なかんじ。caseもある。便利そう。
import Graphics.Element exposing(show) -- if式 direction = if True then "left" else "right" -- if式を利用した関数 isLeft dir = if dir == "left" then True else False -- 複数条件 multiCondition dir = if | dir == "left" -> True | dir == "right" -> False | otherwise -> False -- case caseCondition dir = case dir of "left" -> True "right" -> False _ -> False main = (isLeft direction, multiCondition direction, caseCondition direction) |> show -- (True,True,True)
リスト
同じ型のものを入れることができる。
↓の例ではmapにラムダを入れてる。
import Graphics.Element exposing(show) color = ["white", "black", "red"] colorEmpty = List.isEmpty color -- False colorLen = List.length color -- 3 colorRev = List.reverse color -- ["red","black","white"] main = -- ラムダ式とmap List.map (\x -> x ++ " is good color") color |> show -- ["white is good color","black is good color","red is good color"]
タプルとレコード
タプルは違う型のものを入れるオブジェクトで、レコードは辞書。
レコードの更新が若干独特かもしれない。
import Graphics.Element exposing(show) -- 数値と文字列が混ざったタプル data = (1, "hoge") -- レコード dic = { item = "beer", amount = "500"} -- レコードのアップデート newdic = {dic | amount <- "1000"} main = newdic |> show -- { amount = "1000", item = "beer" }