Skip to content

Instantly share code, notes, and snippets.

@einarwh
Last active May 9, 2021 15:05
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 einarwh/4656b73a7b00e4eed6b1184de3efd761 to your computer and use it in GitHub Desktop.
Save einarwh/4656b73a7b00e4eed6b1184de3efd761 to your computer and use it in GitHub Desktop.
%%% Result: [v T]
%%% Error: [e F]
/ok { % v
[ exch true ] % [v T]
} def
/error { % e
[ exch false ] % [e F]
} def
/map { % A {op} %%% {op} is operation v -> v' to be called for OK results.
[ 3 1 roll % [ A {op}
exch % [ {op} A
aload pop % [ {op} x ?
{ % [ {op} v % map v to op(v)
exch % [ v {op}
exec % [ op(v)
true % [ op(v) T
}
{ % [ {op} e % leave e as is
exch pop false % [ e F
}
ifelse
] % R
} def
/map-error { % A {op} %%% {op} is operation e -> e' to be called for Error results.
[ 3 1 roll % [ A {op}
exch % [ {op} A
aload pop % [ {op} x ?
{ % [ {op} v % leave v as is
exch pop true % [ v T
}
{ % [ {op} e % map e to op(e)
exch % [ e {op}
exec % [ op(e)
false % [ op(e) F
}
ifelse
] % R
} def
/flatmap { % A {op} %%% {op} is operation v -> R to be called for OK results.
exch % {op} A
aload pop % {op} x ?
{ % {op} v % map v to op(v)
exch % v {op}
exec % R=op(v)
}
{ % {op} e % leave e as is
exch pop % e
}
ifelse
} def
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment