Exploring ReasonML 学习笔记 -- 1. Function

296 阅读1分钟

Exploring ReasonML

  1. Passing option values to optional parameters
let multiply = (~x=1, ~y=1, ()) => x * y;

multiply(~x = ?Some(14), ~y = ?None, ()); // 14

~foo = ?foo
~foo? // equivalent to the ~foo =? foo

let square = (~x=?, ()) => multiply(~x?, ~y=?x, ());
  1. Single-argument match functions
let divTuple =
  fun
  | (_, 0) => (-1)
  | (x, y) => x / y;
  1. Operators
(+)(7, 1);

let (+++) = (s, t) => s ++ " " ++ t;

[image:DA85BCBE-66AD-4142-83DF-72AAA68F867E-513-0000F115F3CB4651/B32D2315-3D65-4DB4-ADDD-A6F12389EDE1.png]

let (@-) = (x, y) => x - y;

// According to the operator table, if it starts with an @ symbol, 
// it is automatically right-associative

3 @- 2 @- 1  // 2
  1. Polymorphic functions

polymorphism: making the same operation work for several types

// let id: ('a) => 'a = <fun>;
let id = x => x;  

// ListLabels.map: (~f: ('a) => 'b, list('a)) => list('b)