Sure! Let's rewrite the Leaf encoder/decoder in a language that supports function inversion, allowing us to define both encoding and decoding as inverse operations. A great candidate for this is Haskell, which excels at functional programming, algebraic data types, and bidirectional transformations.
We'll use the lens library (specifically Control.Lens.Iso) to define an isomorphism between the encoded text format and the decoded data structure. This allows us to implement both encoding and decoding in one unified function.
🌟 Why Haskell?
Function Inversion: Haskell allows us to define bidirectional transformations using isomorphisms (Iso).
Type Safety: Strong static typing ensures correctness.
Algebraic Data Types: Nested structures are naturally represented using Haskell's ADTs.
Streaming-Friendly: Lazy evaluation makes it easy to process large files line-by-line.
🔧 Plan
Define the data structure for Leaf documents.
Use an isomorphism (Iso) to encode/decode between the text format and the data structure.
Handle:
Metadata (@key=value)
Dotted-key paths
Type hints (i, f, b, d, s)
Arrays (comma-separated values)
Comments (# ...)
🚀 Haskell Code
haskell
{-# LANGUAGE OverloadedStrings #-}
import Control.Lens ((^.), iso, Iso', view, over)
import Data.Text (Text, pack, unpack, splitOn, strip)
import Data.Time (Day, parseTimeM, defaultTimeLocale)
import Data.Map.Strict (Map, fromList, toList, insertWith)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
-- Data structure for Leaf
type Metadata = Map Text Text
type KeyPath = [Text]
data ValueType = IntVal Int
| FloatVal Float
| BoolVal Bool
| DateVal Day
| StringVal Text
| ArrayVal [Text]
deriving (Show, Eq)
type LeafData = Map KeyPath ValueType
-- Isomorphism for encoding/decoding
leafIso :: Iso' (Metadata, LeafData) Text
leafIso = iso encode decode
where
-- Encode: Convert (Metadata, LeafData) -> Text
encode (meta, dataMap) =
unlines $ map (\(k, v) -> "@" <> k <> "=" <> v) (toList meta)
++ map encodeLine (toList dataMap)
-- Decode: Convert Text -> (Metadata, LeafData)
decode input =
let lines' = map strip (splitLines input)
(metaLines, dataLines) = partition isMeta lines'
meta = fromList [(k, v) | "@":kv <- map (splitOn "=") metaLines, let [k, v] = kv]
dataMap = foldr decodeLine Map.empty dataLines
in (meta, dataMap)
-- Helper: Encode a single line
encodeLine :: (KeyPath, ValueType) -> Text
encodeLine (path, val) = case val of
IntVal i -> key <> ":i=" <> pack (show i)
FloatVal f -> key <> ":f=" <> pack (show f)
BoolVal b -> key <> ":b=" <> pack (if b then "true" else "false")
DateVal d -> key <> ":d=" <> pack (show d)
StringVal s -> key <> "=" <> s
ArrayVal arr -> key <> "=" <> intercalate "," arr
where
key = intercalate "." path
-- Helper: Decode a single line
decodeLine :: Text -> LeafData -> LeafData
decodeLine line acc =
case splitOn "=" line of
[pathWithType, value] ->
let (path, typeHint) = splitType pathWithType
segments = splitOn "." path
in insertWith mergeValues segments (parseValue typeHint value) acc
_ -> acc
-- Split path into segments and optional type hint
splitType :: Text -> (Text, Maybe Text)
splitType path = case reverse (splitOn ":" path) of
(hint:rest) -> (intercalate ":" (reverse rest), Just hint)
_ -> (path, Nothing)
-- Parse value based on type hint
parseValue :: Maybe Text -> Text -> ValueType
parseValue hint val = case hint of
Just "i" -> IntVal (read (unpack val))
Just "f" -> FloatVal (read (unpack val))
Just "b" -> BoolVal (val `elem` ["true", "1", "t", "yes", "y"])
Just "d" -> DateVal (fromMaybe (error "Invalid date") (parseDate val))
_ -> if ',' `elem` val
then ArrayVal (splitOn "," val)
else StringVal val
-- Merge duplicate keys (arrays only)
mergeValues :: ValueType -> ValueType -> ValueType
mergeValues (ArrayVal xs) (ArrayVal ys) = ArrayVal (xs ++ ys)
mergeValues _ y = y
-- Parse date string
parseDate :: Text -> Maybe Day
parseDate = parseTimeM True defaultTimeLocale "%Y-%m-%d"
-- Split lines lazily
splitLines :: Text -> [Text]
splitLines = splitOn "\n"
-- Check if a line is metadata
isMeta :: Text -> Bool
isMeta line = "@" `isPrefixOf` line
🧪 Example Usage
Encoding
haskell
main :: IO ()
main = do
let meta = fromList [("format", "Leaf-1.0"), ("source", "user-db-export")]
let dataMap = fromList [
(["user", "id"], IntVal 42),
(["user", "name"], StringVal "Alice Wonderland"),
(["user", "age"], IntVal 30),
(["user", "verified"], BoolVal True),
(["user", "tags"], ArrayVal ["admin", "editor", "api-user"])
]
putStrLn $ view leafIso (meta, dataMap)
Decoding
haskell
main :: IO ()
main = do
let input = "@format=Leaf-1.0\n\
\@source=user-db-export\n\
\user.id:i=42\n\
\user.name=Alice Wonderland\n\
\user.age:i=30\n\
\user.verified:b=true\n\
\user.tags=admin,editor,api-user"
print $ view (from leafIso) input
🎯 Advantages
Unified Encoding/Decoding: The same function (leafIso) handles both directions.
Type Safety: Errors like invalid dates or malformed arrays are caught at compile time.
Extensibility: Adding new features (e.g., base64 support) is straightforward.
Streaming-Friendly: Lazy evaluation allows processing large files efficiently.
🚨 Limitations
Requires familiarity with Haskell and functional programming concepts.
Parsing errors (e.g., invalid dates) currently throw runtime exceptions; you can improve error handling by using Either.
This implementation leverages Haskell's strengths to create a clean, type-safe, and extensible solution for the Leaf format. If you'd like to explore another language (e.g., Python with libraries like attrs for bidirectional transformations), let me know! 🌿