Skip to content

Instantly share code, notes, and snippets.

@sohang3112
Created August 22, 2024 05:59
Show Gist options
  • Save sohang3112/73a53197d96f7bb731bda2a670076ed1 to your computer and use it in GitHub Desktop.
Save sohang3112/73a53197d96f7bb731bda2a670076ed1 to your computer and use it in GitHub Desktop.
Simple Haskell function to handle HTML attributes that may or may not have a value specified.
-- Simple function to handle HTML attributes that may or may not have a value specified.
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 k] = Just [(k, 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
-- This prints output: Just (fromList [("class",Just "foo bar baz"),("hidden",Nothing),("id",Just "pass"),("required",Nothing)])
main = print $ htmlProps [
key "id", val "pass",
key "required",
key "hidden",
key "class", val "foo bar baz"
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment