Skip to content

Instantly share code, notes, and snippets.

@paf31
Last active August 29, 2015 13:56
Show Gist options
  • Save paf31/8923983 to your computer and use it in GitHub Desktop.
Save paf31/8923983 to your computer and use it in GitHub Desktop.
module Main where
import Prelude
import Parsing
import Either
foreign import data JSON :: *
foreign import toJSON "function toJSON (obj) { return obj; }" :: forall a. a -> JSON
foreign import showJSON "function showJSON (obj) { return JSON.stringify(obj); }" :: JSON -> String
foreign import readProp "function readProp (k) { \
\ return function(typeName) {\
\ return function (obj) { \
\ if (obj.hasOwnProperty(k) && typeof (obj[k]) == typeName) { \
\ return Either.Right(obj[k]);\
\ } \
\ return Either.Left('Unknown property ' + k + ''); \
\ }; \
\ }; \
\};" :: forall a. String -> String -> JSON -> Either String a
instance Prelude.Show JSON where
show = showJSON
toParser :: forall a s. (s -> Either String a) -> Parser s a
toParser p = Parser $ \x -> case (p x) of
(Left err) -> Left $ parseError err
(Right res) -> Right $ parseResult x res
prop :: forall a. String -> String -> Parser JSON a
prop k ty = toParser $ readProp k ty
str :: String -> Parser JSON String
str = flip prop "string"
num :: String -> Parser JSON Number
num = flip prop "number"
bool :: String -> Parser JSON Boolean
bool = flip prop "boolean"
parser :: Parser JSON String
parser = str "foo"
main = do
let obj = toJSON { foo: "hello", bar: true, baz: 1 }
case runParser parser obj of
Left (ParseError err) -> Trace.print err.message
Right (ParseResult { result = res }) -> Trace.print res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment