19

I'm looking to have my Haskell program read settings from an external file, to avoid recompiling for minor changes. Being familiar with YAML, I thought it would be a good choice. Now I have to put the two pieces together. Google hasn't been very helpful so far.

A little example code dealing with reading and deconstructing YAML from a file would be very much appreciated.

2

4 Answers 4

28

If I'm interested in what packages are available, I go to hackage, look at the complete package list, and then just search-in-page for the keyword. Doing that brings up these choices (along with a few other less compelling ones):

and a wrapper around HsSyck called yaml-light: http://hackage.haskell.org/package/yaml-light

Both yaml and HsSyck look updated relatively recently, and appear to be used by other packages in widespread use. You can see this by checking the reverse deps:

Of the two, yaml has more deps, but that is because it is part of the yesod ecosystem. One library that depends on HsSyck is yst, which I happen to know is actively maintained, so that indicates to me that HsSyck is fine too.

The next step in making my choice would be to browse through the documentation of both libraries and see which had the more appealing api for my purposes.

Of the two, it looks like HsSyck exposes more structure but not much else, while yaml goes via the json encodings provided by aeson. This indicates to me that the former is probably more powerful while the latter is more convenient.

2
  • 3
    As a side note, both YAML and HsSyck are actually wrappers around C libraries. YAML is based on libyaml and HsSyck on Syck.
    – Paul R
    Oct 25, 2012 at 15:07
  • 4
    Thanks for demonstrating your review process. It's great to see from a haskell beginner's point of view. Jun 19, 2014 at 1:06
13

A simple example:

First you need a test.yml file:

db: /db.sql
limit: 100

Reading YAML in Haskell

{-# LANGUAGE DeriveGeneric #-}

import GHC.Generics
import Data.Yaml

data Config = Config { db :: String
                     , limit :: Int
                     } deriving (Show, Generic)

instance FromJSON Config

main :: IO ()
main = do
  file <- decodeFile "test.yml" :: IO (Maybe Config)
  putStrLn (maybe "Error" show file)
1
  • I get a deprecationwarning and get told to use decodeFileEither, but drop-in replacement gives me an error. Any idea how the answer could be updated? Seems much more compact than the others.
    – TheChymera
    Dec 4, 2022 at 17:06
1

With yamlparse-applicative you can describe your YAML parser in a static analysis-friendly way, so you can get a description of the YAML format from a parser for free. I'm going to use Matthias Braun's example format for this one:

{-# LANGUAGE ApplicativeDo, RecordWildCards, OverloadedStrings #-}

import Data.Yaml
import Data.Aeson.Types (parse)
import YamlParse.Applicative
import Data.Map (Map)
import qualified Data.Text.IO as T

data MyType = MyType
    { stringsToStrings :: Map String String
    , mapOfLists :: Map String [String]
    } deriving Show

parseMyType :: YamlParser MyType
parseMyType = unnamedObjectParser $ do
    stringsToStrings <- requiredField' "strings_to_strings"
    mapOfLists <- requiredField' "map_of_lists"
    pure MyType{..}

main :: IO ()
main = do
    T.putStrLn $ prettyParserDoc parseMyType

    yaml <- decodeFileThrow "config/example.yaml"
    print $ parse (implementParser parseMyType) yaml

Note that main is able to print out a schema before even seeing an instance:

strings_to_strings: # required
  <key>: <string>
map_of_lists: # required
  <key>: - <string>
Success 
  (MyType 
    { stringsToStrings = fromList
        [ ("key_one","val_one")
        , ("key_two","val_two")
        ]
    , mapOfLists = fromList 
        [ ("key_one",["val_one","val_two","val_three"])
        , ("key_two",["val_four","val_five"])
        ]
    })
0

Here's how to parse specific objects from your YAML file using the yaml library.

Let's parse parts of this file, config/example.yaml:

# A map from strings to strings
strings_to_strings:
      key_one: val_one
      key_two: val_two

# A map from strings to list of strings
map_of_lists:
  key_one:
      - val_one
      - val_two
      - val_three
  key_two:
      - val_four
      - val_five

# We won't parse this
not_for: us

This module parses strings_to_strings and map_of_lists individually and puts them into a custom record, MyType:

{-# Language OverloadedStrings, LambdaCase #-}
module YamlTests where
import           Data.Yaml                      ( decodeFileEither
                                                , (.:)
                                                , parseEither
                                                , prettyPrintParseException
                                                )
import           Data.Map                       ( Map )
import           Control.Applicative            ( (<$>) )
import           System.FilePath                ( FilePath
                                                , (</>)
                                                )

data MyType = MyType {stringsToStrings :: Map String String,
                      mapOfLists :: Map String [String]} deriving Show
type ErrorMsg = String

readMyType :: FilePath -> IO (Either ErrorMsg MyType)
readMyType file =
  (\case
      (Right yamlObj) -> do
        stringsToStrings <- parseEither (.: "strings_to_strings") yamlObj
        mapOfLists       <- parseEither (.: "map_of_lists") yamlObj
        return $ MyType stringsToStrings mapOfLists
      (Left exception) -> Left $ prettyPrintParseException exception
    )
    <$> decodeFileEither file

yamlTest = do
  parsedValue <- readMyType $ "config" </> "example.yaml"
  print parsedValue

Run yamlTest to see the parsing result.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.