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.
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
htmlProps [
key "id", val "pass",
key "required",
key "hidden",
key "class", val "foo bar baz"
]
Just (fromList [("class",Just "foo bar baz"),
("hidden",Nothing),
("id",Just "pass"),
("required",Nothing)])
- Instead of
Maybe
,htmlProps
should returnEither
indicating position and value where error occured.