Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading YAML in Haskell

Tags:

yaml

haskell

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.

like image 441
mkaito Avatar asked Oct 25 '12 00:10

mkaito


2 Answers

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):

  • yaml: http://hackage.haskell.org/package/yaml
  • HsSyck: http://hackage.haskell.org/package/HsSyck

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:

  • http://packdeps.haskellers.com/reverse/HsSyck
  • http://packdeps.haskellers.com/reverse/yaml

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.

like image 54
sclv Avatar answered Nov 06 '22 02:11

sclv


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)
like image 24
Manuel Avatar answered Nov 06 '22 02:11

Manuel