Sto scrivendo una piccola libreria per l'interazione con alcune API esterne. Un insieme di funzioni costruisce una richiesta valida per l'API di yahoo e analizza il risultato in un tipo di dati. Un altro set di funzioni cercherà la posizione attuale dell'utente in base all'IP e restituirà un tipo di dati che rappresenta la posizione corrente. Mentre il codice funziona, sembra che debba associare in modo esplicito la corrispondenza alla sequenza di più funzioni di tipo IO (forse a).Funzioni di concatenamento di tipo IO (Forse a)
-- Yahoo API
constructQuery :: T.Text -> T.Text -> T.Text
constructQuery city state = "select astronomy, item.condition from weather.forecast" <>
" where woeid in (select woeid from geo.places(1)" <>
" where text=\"" <> city <> "," <> state <> "\")"
buildRequest :: T.Text -> IO ByteString
buildRequest yql = do
let root = "https://query.yahooapis.com/v1/public/yql"
datatable = "store://datatables.org/alltableswithkeys"
opts = defaults & param "q" .~ [yql]
& param "env" .~ [datatable]
& param "format" .~ ["json"]
r <- getWith opts root
return $ r ^. responseBody
run :: T.Text -> IO (Maybe Weather)
run yql = buildRequest yql >>= (\r -> return $ decode r :: IO (Maybe Weather))
-- IP Lookup
getLocation:: IO (Maybe IpResponse)
getLocation = do
r <- get "http://ipinfo.io/json"
let body = r ^. responseBody
return (decode body :: Maybe IpResponse)
- Combinator
runMyLocation:: IO (Maybe Weather)
runMyLocation = do
r <- getLocation
case r of
Just ip -> getWeather ip
_ -> return Nothing
where getWeather = (run . (uncurry constructQuery) . (city &&& region))
E 'possibile infilare getLocation e correre insieme senza ricorrere a modello esplicita corrispondenza di "uscire" del Forse Monade?
A proposito, perché questo è un anti-pattern? – Yuuri
@Yuuri, perché sembra che otterrai sempre un risultato o "Niente", ma potresti ottenere, ad esempio, un'eccezione di timeout di rete. – dfeuer
Non vedo perché pensi che sembri "sempre un risultato di' Nothing' ". La maggior parte degli Haskeller dovrebbe essere abbastanza familiare con i trasformatori monad per sapere come funzionano "dentro e fuori". – leftaroundabout