快速開發大型 javascript 專案—reason(上)
看過一些 reason 的視訊教程,Reason 優勢就是速度,開發速度。
字串
let multilineGreeting = "Hello world!";
字串支援多行,
字串的連線
let greetings = "Hello " ++ "world111!";
Record
- 更輕量級
- 預設是不可變型別
- 欄位名稱和型別是固定的
- 高效
type person = {age: int, name: string}; let matthew:person = { age:30, name:"matthew" }
注意為什麼他是輕量級呢?因為編譯 javascript 他程式設計了陣列而不是物件。
var matthew = /* record */[ /* age */30, /* name */"matthew" ];
集合
let myArray = [|"hello", "world", "how are you"|]; Js.log(myArray[3])
Invalid_argument,-3,index out of bounds
編譯後,發現在編譯的 javascript 檔案多出了
var Caml_array = require("bs-platform/lib/js/caml_array.js");
Variant
強大的功能,體驗一下
type myResponseVariant = | Yes | No | PrettyMuch; let areYouCrushingIt = No let message = switch (areYouCrushingIt) { | No => "No worries. Keep going!" | Yes => "Great!" | PrettyMuch => "Nice!" };
體驗一下的確挺強大,感覺自己有點喜歡 ocaml,看吧上面程式碼無論是看起來還寫起來都是那麼舒服。做分支語句好舒服呀。
函式
ocaml 應該是天生支援函數語言程式設計,所以函式是重頭戲,我們看一看。
函式的聲名使用箭頭返回一個表示式
let greet = (name) => "Hello " ++ name; Js.log(greet("matthew"))
如果函式體是多行的呢,就用一個大括號
let greetMore = (name) => { let part1 = "Hello"; part1 ++ " " ++ name };
我們可以為引數新增標籤,在引數前面加上~,這樣我們就可以調整順序
let addCoordinates = (~x, ~y) => { /* use x and y here */ }; /* ... */ addCoordinates(~x=5, ~y=6);
curry 化
let add = (x, y) => x + y; let addFive = add(5); let eleven = addFive(6); let twelve = addFive(7);
在 reason 函式是自動可以轉換為偏函式,上面程式碼就是證明,暫時先不深究了。
鏈式呼叫
validateAge(getAge(parseData(person))) person ->parseData ->getAge ->validateAge