Skip to content

Instantly share code, notes, and snippets.

@sigma-andex
Created October 30, 2021 16:58
Show Gist options
  • Save sigma-andex/fd2fb56b205d1df8177d9b11de58ce19 to your computer and use it in GitHub Desktop.
Save sigma-andex/fd2fb56b205d1df8177d9b11de58ce19 to your computer and use it in GitHub Desktop.
TS Enum representation
"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
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
@sigma-andex
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment