匯出函式在第一個概念中介紹過了,這裡快速複習一下。
Elm 中的每個檔案都是一個模組,而且必須在所有其他程式碼之前包含一個module敘述。
模組名稱必須與檔案名稱相符,所以模組Calculator必須放在 Calculator.elm 檔案中,而模組Parser.Utils則需要放在 Parser/Utils.elm 檔案中。
模組內定義的任何東西都是該模組私有的,無法從這個模組外部存取,除非列在exposing中。
-- Calculator.elm
-- Define the Calculator module, and expose the `add` function
module Calculator exposing (add)
six = 3 + 3
add number1 number2 = number1 + number2
-- Calculator.elm
-- Define the Calculator module, and expose everything within: `six` and `add`
module Calculator exposing (..)
six = 3 + 3
add number1 number2 = number1 + number2
https://elm-lang.org/docs/syntax#modules
要存取定義在其他模組中的函式,需要透過匯入來完成。 匯入該模組時,所有由它匯出的函式都會變成可存取的。 但存取它們的方式會依匯入模組的方式而有所不同。
限定匯入是預設方式,要存取這類模組中的函式(例如List模組中的map函式),需要在前面加上模組名稱(List.map)。
開放匯入則可以直接存取該模組中匯出的函式,不需要加上前綴。它們是透過exposing關鍵字完成的,就像是匯出時所用關鍵字的鏡像。你可以匯出所有可用的函式(使用..),或是特定的函式(例如map)。
你也可以從其他模組匯入型別及其建構子,這會是之後的概念。
建議優先使用限定匯入,以幫助維持清晰並避免名稱衝突。
-- qualified imports
import List -- List.map, List.foldl
import List as L -- L.map, L.foldl
-- open imports
import List exposing (..) -- map, foldl, concat, ...
import List exposing ( map, foldl ) -- map, foldl, List.concat
https://elm-lang.org/docs/syntax#modules
型別註解是用name : parameter types -> return type定義的,參數型別之間也用->分隔。
add : Int -> Int -> Int
add number1 number2 = number1 + number2
括號可以用來定義函式參數(參數本身也是用相同的語法定義,所以才需要括號)。
-- Transform every character in a string
map : (Char -> Char) -> String -> String
map charMapperFunction string =
-- ...
https://elm-lang.org/docs/syntax#type-annotations
Elm 中有兩種可用的數字型別,分別由Int和Float型別定義。
Int對應到正整數與負整數的集合。
Float對應到實數的集合,受限於電腦的精確度。
定義在數字上的運算通常只適用於其中一種型別,不能混用。
有些函式可以在兩者之間轉換,例如toFloat會將Int轉成Float,而round、floor、ceiling或truncate則會以不同的語意將Float轉成Int。
https://package.elm-lang.org/packages/elm/core/latest/Basics#Int
若要在程式碼中描述單字和句子,Elm 有原生的String型別。
字串常值寫在雙引號之間,例如"Hello World!"。
預設可以使用字串串接運算子++和相等運算子==。
hello : String -> String
hello subject = "Hello " ++ subject
hello "World!" --> "Hello World!"
大多數其他的字串函式都在String模組中,需要先匯入。
https://package.elm-lang.org/packages/elm/core/latest/String
在這個練習中,你將寫一些程式碼來協助 Betty's Bike Shop,這是一間販售自行車與零件的線上商店。你有三個任務,目標是在網站上正確顯示自行車與零件的價格。
penceToPounds函式你的同事已經寫好了這個模組的骨架,也就是尚未定義的penceToPounds和poundsToString兩個函式。
不過,他們忘了匯出penceToPounds函式,所以它目前無法被其他模組或測試套件看見。
請把penceToPounds加入已匯出函式的清單中。
目前,價格是以整數的便士儲存的(這間自行車店位於英國)。
在網站上,我們想以英鎊顯示價格,其中 1.00 英鎊等於 100 便士。
你的第二個任務是實作penceToPounds函式,它接受Int型別的便士數量,並把它轉換成等值的英鎊,型別為Float。
你也應該為這個函式定義型別註解。
penceToPounds 106
--> 1.06
由於 Betty's Bike Shop 的自行車是以英鎊販售,價格應該以符號「£」顯示。
因此你的第三個任務是實作poundsToString函式,它接受Float型別的英鎊金額,並回傳加上英鎊符號後所顯示的價格,型別為String。
String模組裡的String.fromFloat函式會對你很有幫助。
使用之前,你應該先匯入String模組。
你也應該為poundsToString定義型別註解。
poundsToString 1.06
--> "£1.06"