MattCheely / boon / Boon

Parsing and evaulation of Boon strings.

Terminology

In the boon expression:

this OR that

OR is an operator, and this and that are identifiers.

Parsing


type Expression i

A parsed Boon expression with identifiers of type i. Can be evaluated many times

parse : String -> Result String (Expression String)

Try to parse a string as a Boon expression, failing on invalid input.

parseWith : (String -> Result String i) -> String -> Result String (Expression i)

Try to parse a string as a Boon expression, using the provided function to transform identifiers. This can be useful if your Boon expressions have more than one type of identifier in them and you want to map them to custom types.

type Ingredient
    = Meat String
    | Cheese String

parseIngredient : String -> Result String Ingredient
parseIngredient str =
    case String.split ":" str of
        "meat" :: rest ->
            Ok (Meat (String.concat rest))

        "cheese" :: rest ->
            Ok (Cheese (String.concat rest))

        _ ->
            Err (str ++ " is not a valid ingredient")

sandwichCheck : Ingredient -> Bool
sandwichCheck ingredient =
    case ingredient of
        Meat "ham" ->
            True
        Cheese "swiss" ->
            True

-- returns True
parseWith parseIngredient "meat:ham AND cheese:swiss"
    |> eval sandwichCheck

Evaluation

eval : (i -> Basics.Bool) -> Expression i -> Basics.Bool

Evaluate an expression based on a user-provided lookup function that maps identifiers to boolean values.

trueOrFalse str =
    if (str == "true") then
        True
    else
        False

-- Evaluates to False
parse "true AND false"
    |> eval trueOrFalse

evalFromDict : Dict comparable Basics.Bool -> Expression comparable -> Basics.Bool

Evaluate an expression by looking up identifiers in a Dict. If a key is absent, it will evaluate to False

values =
    Dict.fromList
        [ ( "foo", True )
        , ( "bar", False )
        ]

-- Evaluates to True
parse "foo OR bar"
    |> evalFromDict values

-- Evaluates to False
parse "baz OR bar"
    |> evalFromDict values

evalFromSet : Set comparable -> Expression comparable -> Basics.Bool

Evalute an expression by looking up identifiers in a Set. Identifiers present in the set are True, any others are False.

values = Set.fromList ["foo", "bar"]

-- Evaluates to True
parse "foo AND bar"
    |> evalFromSet values

-- Evaluates to False
parse "bar AND baz"
    |> evalFromSet values

identifiers : Expression i -> List i

Get a list of identifiers used in an expression. This can be useful if you need to fetch these identifiers from some external source with a Cmd prior to evaluation, or otherwise keep a list of them for reference.

Identifiers may be included more than once and ordering is not guaranteed. It is recommended to collect them in a Set if the identifiers are comparable.