Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Combinator for defining a grammar by enumeration #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/Language/JsonGrammar/Grammar.hs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import Data.StackPrism (StackPrism, forward, backward, (:-)(..))
import Data.String (IsString(..))
import Data.Text (Text)
import Language.TypeScript (Type(..), PredefinedType(..))

import qualified Data.Aeson as Aeson


-- Types
Expand Down Expand Up @@ -201,3 +201,14 @@ defaultValue x = Pure f g
-- | Create a 'pure' grammar from a 'StackPrism'.
fromPrism :: StackPrism a b -> Grammar c a b
fromPrism p = Pure (return . forward p) (backward p)

-- | Define a grammar by enumerating the possible values
--
-- For example:
--
-- > bool :: Grammar Val (Value :- t) (Bool :- t)
-- > bool = enumeration [(True, "true"), (False, "false")]
enumeration :: Eq a => [(a, Text)] -> Grammar Val (Value :- t) (a :- t)
enumeration = mconcat . map aux
where
aux (a, txt) = defaultValue a . literal (Aeson.String txt)