Skip to content

Instantly share code, notes, and snippets.

@kxbmap
Created June 28, 2012 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kxbmap/3012418 to your computer and use it in GitHub Desktop.
Save kxbmap/3012418 to your computer and use it in GitHub Desktop.
SquirrelでOption
dofile("Option.nut");
local println = @(line) print(line + "\n");
println(Some(1).map(@(v) v + 1)); // => Some(2)
println(None.map(@(v) v + 1)); // => None
println(Some(2).flatMap(@(v) ::Some(v * 2))); // => Some(4)
println(None.flatMap(@(v) ::Some(v * 2))); // => None
println(Some(3).filter(@(v) v > 2)); // => Some(3)
println(Some(2).filter(@(v) v > 2)); // => None
println(None.filter(@(_) true)); // => None
println(Some(1).getOrElse(@() 0)); // => 1
println(None.getOrElse(@() 0)); // => 0
println(Some(2).orElse(@() Some(0))); // => Some(2)
println(None.orElse(@() Some(0))); // => Some(0)
foreach (k, v in Some(100)) {
println("k:" + k + ", v:" + v); // => k:0, v:100
}
foreach (_ in None) {
println("unreach"); // 実行されない
}
class Option {}
class Some extends Option {
constructor(value) {
this.value = value;
}
function map(f) {
return ::Some(f(value));
}
function flatMap(f) {
return f(value);
}
function filter(f) {
return f(value) ? this : ::None;
}
function getOrElse(_) {
return value;
}
function orElse(_) {
return this;
}
function _nexti(prev) {
return prev == null ? 0 : null;
}
function _get(idx) {
::assert(idx == 0);
return value;
}
function _tostring() {
return "Some(" + value + ")";
}
value = null;
}
local none = class extends Option {
function map(_) {
return this;
}
function flatMap(_) {
return this;
}
function filter(_) {
return this;
}
function getOrElse(f) {
return f();
}
function orElse(f) {
return f();
}
function _nexti(_) {
return null;
}
function _tostring() {
return "None";
}
}
None <- none();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment