Created
October 30, 2021 16:58
-
-
Save sigma-andex/fd2fb56b205d1df8177d9b11de58ce19 to your computer and use it in GitHub Desktop.
TS Enum representation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict" | |
exports.x = 15 | |
exports.y = 16 | |
const numberSyntax = 15 | |
exports.numberSyntax = numberSyntax | |
const stringSyntax = 16 | |
exports.stringSyntax = stringSyntax | |
const isMatchImpl = function (x, y) { | |
return x === y | |
} | |
exports.isMatchImpl = isMatchImpl | |
const matchImpl = function (matchNumber, matchString, input) { | |
if (isMatchImpl(input, numberSyntax)) { | |
return matchNumber(input) | |
} else { | |
if (isMatchImpl(input, stringSyntax)) { | |
return matchString(input) | |
} else { | |
return undefined | |
} | |
} | |
} | |
exports.matchImpl = matchImpl |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main where | |
import Prelude | |
import Data.Function.Uncurried (Fn2, Fn3, runFn2, runFn3) | |
import Debug (spy) | |
import Effect (Effect) | |
import Effect.Class.Console (log, logShow) | |
data SyntaxEnum | |
foreign import data NumberSyntax :: SyntaxEnum | |
foreign import data StringSyntax :: SyntaxEnum | |
data Syntax :: SyntaxEnum -> Type | |
data Syntax k | |
foreign import numberSyntax :: Syntax NumberSyntax | |
foreign import stringSyntax :: Syntax StringSyntax | |
foreign import isMatchImpl :: forall s. Fn2 SyntaxEnum (Syntax s) Boolean | |
isMatch :: forall s. SyntaxEnum -> Syntax s -> Boolean | |
isMatch = runFn2 isMatchImpl | |
foreign import matchImpl :: | |
forall output. | |
Fn3 | |
(Syntax NumberSyntax -> output) | |
(Syntax StringSyntax -> output) | |
SyntaxEnum | |
output | |
match :: forall output. (Syntax NumberSyntax -> output) -> (Syntax StringSyntax -> output) -> SyntaxEnum -> output | |
match = runFn3 matchImpl | |
foreign import x :: SyntaxEnum | |
foreign import y :: SyntaxEnum | |
type Node | |
= { kind :: Syntax StringSyntax | |
} | |
n :: Node | |
n = | |
{ kind: stringSyntax -- numberSyntax results in error | |
} | |
main :: Effect Unit | |
main = do | |
let | |
_ = spy "x" x | |
_ = spy "y" y | |
logShow $ isMatch x numberSyntax | |
logShow $ isMatch x stringSyntax | |
logShow $ isMatch y numberSyntax | |
logShow $ isMatch y stringSyntax | |
let | |
f = match (const "Got a number") (const "Got a string") | |
log $ f x | |
log $ f y | |
pure unit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Typescript enums documentation: https://www.typescriptlang.org/docs/handbook/enums.html