Skip to content

Instantly share code, notes, and snippets.

@michaelt
Created May 17, 2015 16:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelt/85e07eeb55838578bacb to your computer and use it in GitHub Desktop.
Save michaelt/85e07eeb55838578bacb to your computer and use it in GitHub Desktop.
weather.hs
{-# LANGUAGE OverloadedStrings #-}
module Main where
import System.Environment
import Data.Monoid
import Control.Monad
import Data.Aeson
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.HTTP.Client
import Data.ByteString.Lazy (ByteString)
type URL = String
type City = String
type Code = String
type Emoji = T.Text
data Weather = Weather { code :: String }
instance FromJSON Weather where
parseJSON (Object o) = do
weatherValues <- o .: "weather"
case weatherValues of
[] -> mzero
weatherValue:_ -> Weather <$> weatherValue .: "icon"
parseJSON _ = mzero
apiUrl :: URL
apiUrl = "http://api.openweathermap.org/data/2.5/weather?q="
urlBuilder :: City -> URL
urlBuilder city = apiUrl <> city <> "&units=metric"
simplestHttp :: URL -> IO ByteString
simplestHttp str = do
req <- parseUrl str
withManager defaultManagerSettings $ \mgr -> do
resp <- httpLbs req mgr
return (responseBody resp)
getWeather :: City -> IO (Maybe Weather)
getWeather city = do -- fmap decode . simplestHttp
resp <- simplestHttp city
return (decode resp :: Maybe Weather)
getEmoji :: Code -> Emoji
getEmoji code = case take 2 code of
"01" -> "☀️" -- sun
"02" -> "⛅️" -- sun with cloud
"03" -> "☁️" -- cloud
"04" -> "☁️" -- cloud
"09" -> "💦" -- rain
"10" -> "💦" -- rain
"11" -> "⚡️" -- thunder
"13" -> "❄️" -- snow
"50" -> "♒︎" -- mist
_ -> "⁉️"
parseArgs = do
args <- getArgs
case args of
[s]-> return s
_ -> error "No City given."
main = do
city <- parseArgs
response <- getWeather city
case response of
Just w -> T.putStrLn $ getEmoji (code w)
Nothing -> error "Failed to fetch weather info."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment