Haskell:
Working with YAML

How to:

Haskell does not have built-in support for YAML processing, but you can use third-party libraries such as yaml and aeson for parsing and generating YAML data. Here’s how you can get started:

Reading YAML

First, add the yaml package to your project’s dependencies. Then, you can use the following example to parse a simple YAML document:

{-# LANGUAGE OverloadedStrings #-}

import Data.YAML
import Data.ByteString (ByteString)
import Control.Monad.IO.Class (liftIO)

-- Example YAML data
yamlData :: ByteString
yamlData = "
name: John Doe
age: 30
"

-- Define a data structure that matches the YAML document
data Person = Person
  { name :: String
  , age :: Int
  } deriving (Show)

instance FromYAML Person where
  parseYAML = withMap "Person" $ \m -> Person
    <$> m .: "name"
    <*> m .: "age"

main :: IO ()
main = do
  let parsed = decode1 yamlData :: Either (Pos,String) Person
  case parsed of
    Left err -> putStrLn $ "Error parsing YAML: " ++ show err
    Right person -> print person

Sample output for the above code might look like:

Person {name = "John Doe", age = 30}

Writing YAML

To generate YAML from Haskell data structures, you can use the yaml package’s encoding functionalities as shown below:

{-# LANGUAGE OverloadedStrings #-}

import Data.YAML
import Data.ByteString.Lazy.Char8 (unpack)

-- Using the Person data structure from the previous example

person :: Person
person = Person "Jane Doe" 25

main :: IO ()
main = do
  let yamlData = encode1 person
  putStrLn $ unpack yamlData

The output of this program will be a YAML-formatted string:

name: Jane Doe
age: 25

These examples should serve as a starting point for working with YAML in Haskell. Depending on your needs, you might want to explore more advanced features and options provided by these libraries.