Skip to content

Instantly share code, notes, and snippets.

@sohang3112
Created June 29, 2022 04:57
Show Gist options
  • Save sohang3112/7962513fb92271d44bfda5450d40204c to your computer and use it in GitHub Desktop.
Save sohang3112/7962513fb92271d44bfda5450d40204c to your computer and use it in GitHub Desktop.
Resolve HTML Properties into a `Map`, while also dealing with missing / default property values

Description

In HTML, while defining elements, property values can be omitted. Here, the htmlProps function takes a list of property keys or values, and resolves it into a Map of keys to values by the following rules: - A Key followed by a Val associates the key with the val in result map. - A Key followed by another Key means the first key has value Nothing in result map. - A Val without a Key before it indicates an error.

Code

import qualified Data.Map as Map
import Data.Map (Map)

-- HTML Property Key | Value
type Prop k v = Either k v

key = Left
val = Right

htmlProps :: Ord k => [Prop k v] -> Maybe (Map k (Maybe v))
htmlProps = fmap Map.fromList . go
  where go :: [Prop k v] -> Maybe [(k, Maybe v)]
        go [] = Just []
        go [Left x] = Just [(x, Nothing)]
        go (Left k : rest@(Left _ : _)) = ((k, Nothing) :) <$> go rest
        go (Left k : Right v : rest) = ((k, Just v) :) <$>  go rest
        go (Right _ : _) = Nothing

Example Usage

Input

htmlProps [
        key "id", val "pass",
        key "required",
        key "hidden",
        key "class", val "foo bar baz"
      ]

Output (Prettified)

Just (fromList [("class",Just "foo bar baz"),
                ("hidden",Nothing),
                ("id",Just "pass"),
                ("required",Nothing)])

TODO

  • Instead of Maybe, htmlProps should return Either indicating position and value where error occured.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment