-
Notifications
You must be signed in to change notification settings - Fork 0
Haskell Example Code
MMDRZA edited this page Oct 18, 2024
·
1 revision
{-# LANGUAGE OverloadedStrings #-}
import Data.Aeson (eitherDecode, (.:), FromJSON, parseJSON, withObject)
import Network.HTTP.Simple (httpLBS, getResponseBody, parseRequest)
import qualified Data.ByteString.Lazy.Char8 as LBS
import Control.Monad (forM_)
-- Define a Coin data type to hold information about each cryptocurrency
data Coin = Coin
{ symbol :: String
, lastPrice :: String
, highPrice24h :: String
, lowPrice24h :: String
, changeRate :: String
, lastUpdated :: String
} deriving (Show)
-- Implement the FromJSON instance to parse the JSON response
instance FromJSON Coin where
parseJSON = withObject "Coin" $ \v -> Coin
<$> v .: "symbol"
<$> v .: "lastPrice"
<$> v .: "highPrice24h"
<$> v .: "lowPrice24h"
<$> v .: "changeRate"
<$> v .: "lastUpdated"
-- Function to fetch and display cryptocurrency data
fetchCryptoData :: IO ()
fetchCryptoData = do
let url = "https://raw.githubusercontent.com/Crypto-Static/Rate/main/rateStatic.json"
request <- parseRequest url
response <- httpLBS request
let body = getResponseBody response
case eitherDecode body of
Left err -> putStrLn $ "Error parsing JSON: " ++ err
Right coins -> forM_ coins $ \coin -> do
putStrLn $ "Symbol: " ++ symbol coin ++
" | LAST: " ++ lastPrice coin ++
" | HIGH: " ++ highPrice24h coin ++
" | LOW: " ++ lowPrice24h coin ++
" | CHANGE: " ++ changeRate coin ++
" | UPDATED: " ++ lastUpdated coin
-- Main function to run the script
main :: IO ()
main = fetchCryptoData
You need to install the Aeson
and HTTP
libraries. You can do this using the following commands:
cabal install aeson
cabal install http-conduit
Save the Haskell script and run it using cabal
or ghc
:
runghc fetch_crypto_data.hs
👨💻 Programmer : PyMmdrza 🌍 Official Website Mmdrza.Com 📧 Email : [email protected]
📧 [email protected]