Skip to content

Instantly share code, notes, and snippets.

@kamalmarhubi
Last active December 16, 2015 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamalmarhubi/5473399 to your computer and use it in GitHub Desktop.
Save kamalmarhubi/5473399 to your computer and use it in GitHub Desktop.
{-# LANGUAGE OverloadedStrings #-}
-- The Haskell String type is a linked list of characters, and according to the
-- Haskell Report, literal strings have this type. There are better
-- representations like Data.Text and ByteString, which use packed arrays of
-- characters. OverloadedStrings is a language extension that lets you use
-- sting literals in places where these other representations are expected,
-- without needing conversion functions. In this file, that's happening in the
-- object property getters in parseJson -- (.:) takes a Data.Text, and you want
-- to call it more conveniently with a string literal.
import Network.HTTP.Conduit
import Control.Monad.IO.Class -- needed because you use it in a type signature
import qualified Data.ByteString.Lazy as B -- needed because you use it in a type signature
import Data.Aeson
import Data.Attoparsec.Number -- needed because you use the type
import Control.Applicative -- needed to get the <*> and <$> operators
-- import Control.Monad.Trans -- not actually needed
-- You can actually get rid of the ByteString import if you just remove the
-- type signature for `get`. The signature for `ticker` can't be removed in the
-- same way because the type system needs to be told to it returns a Ticker
-- value, so the MonadIO import has to hang around as well. If you *really*
-- wanted to get rid of it, you could change main to:
--
-- main = do
-- v <- ticker
-- print (v :: Maybe Ticker)
--
-- which gives that information to the type system somewhere where it doesn't
-- also need to know about MonadIO. I woudn't do that myself, I'd just get used
-- to seeing the type classes around the place.
data Ticker = Ticker
{ high :: Number,
last :: Number,
bid :: Number,
volume :: Number,
low :: Number,
ask :: Number
} deriving Show
instance FromJSON Ticker where
parseJSON (Object v) = Ticker
<$> (v .: "high")
<*> (v .: "last")
<*> (v .: "bid")
<*> (v .: "volume")
<*> (v .: "low")
<*> (v .: "ask")
ticker::(MonadIO m) => m (Maybe Ticker)
ticker = get "ticker" >>= return . decode
get::(MonadIO m) => String -> m B.ByteString
get url = simpleHttp $ "https://www.bitstamp.net/api/"++url
main = do
ticker >>= print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment