Prelude.read: нет синтаксического анализа && Не удалось сопоставить ожидаемый тип «Double» с фактическим типом «Text» В первом аргументе «WeatherValues», а именно «tempMin» - PullRequest
0 голосов
/ 16 мая 2018

Как я могу это исправить? Couldn't match expected type ‘Double’ with actual type ‘Text’ Я не могу использовать текст вместо двойного. И это ответ

Ответ

{responseStatus = Status {statusCode = 200, statusMessage = "OK"}, 
responseVersion = HTTP/1.1, responseHeaders = [("Server","openresty"),
("Date","Wed, 16 May 2018 11:12:26 GMT"),("Content-Type","application/json; 
charset=utf-8"),("Content-Length","446"),("Connection","keep-alive"),("X-Cache-
Key","/data/2.5/weather?q=yerevan,am"),("Access-Control-Allow-Origin","*"),
("Access-Control-Allow-Credentials","true"),("Access-Control-Allow-
Methods","GET, POST")], responseBody = "{\"coord\":
{\"lon\":44.51,\"lat\":40.18},\"weather\":
[{\"id\":801,\"main\":\"Clouds\",\"description\":\"few 
clouds\",\"icon\":\"02d\"}],\"base\":\"stations\",\"main\":
{\"temp\":298.15,\"pressure\":1019,\"humidity\":23,\"temp_min\":298.15,\"temp_ma
x\":298.15},\"visibility\":10000,\"wind\":
{\"speed\":1.5,\"deg\":220},\"clouds\":{\"all\":20},\"dt\":1526466600,\"sys\":
{\"type\":1,\"id\":7226,\"message\":0.0032,\"country\":\"AM\",\"sunrise\":152643
5114,\"sunset\":1526487120},\"id\":616052,\"name\":\"Yerevan\",\"cod\":200}", 
responseCookieJar = CJ {expose = []}, responseClose' = ResponseClose}

Код:

{-# LANGUAGE DeriveGeneric     #-}
{-# LANGUAGE OverloadedStrings #-}    

module PrepareAnswer where

import           Control.Monad
import           Data.Maybe
import           GHC.Generics

import           Data.Aeson
import           Data.Aeson.Types
import qualified Data.ByteString          as BS
import qualified Data.ByteString.Lazy     as BSL
import           Data.Text
import           Network.HTTP.Client
import           Text.Read
import           Data.Text         
import           Text.JSON
import           AskWeather

data WeatherValues = WeatherValues
               { temp_min :: Double          
            -- , temp_max :: Text
            -- , pressure :: Text
            -- , speed     :: Text
               } deriving (Show) -- Здесь speed подразумевается как скорость ветра

prepareAnswer :: Response BSL.ByteString -> Text
prepareAnswer response = Data.Text.pack . show $ weatherValues
    where
      --finalPhrase = createFinalPrase preparedValues
    --  preparedValues = prepareValues weatherValues
        weatherValues = extractValues . responseBody $ response

extractValues :: BSL.ByteString -> WeatherValues
extractValues rawJSON =
    let result  = decode' rawJSON
    in case result of
        Nothing   -> error "Invalid JSON!"
        Just info -> 
                let  tempMin   = getTempMin info
          --       tempMax   = getTempMax   info
           --      pressInfo = getPressure  info
           --  windSpeed = getWindSpeed info
        in WeatherValues tempMin -- tempMax pressInfo windSpeed

getTempMin :: Object -> Text
getTempMin info =
    case parseMaybe extractTempMin info of 
        Nothing -> "Invalid JSON!"
        Just info -> info 
    where
        extractTempMin = \info -> info .: "main"
                         >>=
                         \mainInfo -> mainInfo .: "temp_min"

1 Ответ

0 голосов
/ 16 мая 2018

Эти три фрагмента из вашего кода несовместимы:

data WeatherValues = WeatherValues
           { temp_min :: Double
           }

let tempMin = getTempMin info
in WeatherValues tempMin

getTempMin :: Object -> Text

Вероятно, правильное решение - настроить getTempMin для возврата Maybe Double (возможно, путем синтаксического анализа Text, который вы извлекаете некоторым образом), а также настроить extractValues для возврата Maybe WeatherValues.

...