praxis

Various programming exercises.
git clone git://git.jtobin.io/praxis.git
Log | Files | Refs

Currency.hs (909B)


      1 {-# OPTIONS_GHC -Wall #-}
      2 {-# LANGUAGE OverloadedStrings #-}
      3 
      4 module Currency (query) where
      5 
      6 import Control.Lens
      7 import Data.Aeson
      8 import Data.Aeson.Lens
      9 import Data.Monoid
     10 import Data.Scientific (Scientific)
     11 import Data.Text (Text)
     12 import qualified Data.Text as Text
     13 import Network.Wreq
     14 
     15 apiUrl :: String
     16 apiUrl = "http://www.freecurrencyconverterapi.com/api/v3/convert"
     17 
     18 convertQuery :: String -> String -> String
     19 convertQuery x y = apiUrl <> "?q=" <> x <> "_" <> y <> "&compact=y"
     20 
     21 tp :: String -> Text
     22 tp = Text.pack
     23 
     24 query :: Scientific -> String -> String -> IO Scientific
     25 query d x y = do
     26   r <- asJSON =<< get (convertQuery x y) :: IO (Response Value)
     27   let replyBody = do
     28         reply <- r ^? responseBody . key (tp x <> "_" <> tp y) . _Object
     29         val   <- reply ^. at "val"
     30         val ^? _Number
     31 
     32   case replyBody of
     33     Nothing -> error "invalid currency pair"
     34     Just v  -> return $ d * v
     35