Explicit type conversion?

This is an example function:

import qualified Data.ByteString.Lazy as LAZ
import qualified Data.ByteString.Lazy.Char8 as CHA
import Network.Wreq

makeRequest :: IO (Network.Wreq.Response LAZ.ByteString)
makeRequest = do 
   res <- get "http://www.example.com" 
   let resBody = res ^. responseBody :: CHA.ByteString
   --Do stuff....
   return (res)

I am trying to understand the exact purpose of CHA.ByteString in this line:

let resBody = res ^. responseBody :: CHA.ByteString

Is it explicitly stated that the type must be CHA.ByteString? Or does it serve a different role?

+4
source share
2 answers

Yes, it is explicitly stated what type should be CHA.ByteString. This in itself does not require any conversion, it is just a hint to the compiler (and / or reader) that resthis type should be.

These types of local annotations are necessary when the value is obtained from a function with a polymorphic result and is only consumed by functions with a polymorphic argument. A simple example:

f :: Int -> Int
f = fromEnum . toEnum

toEnum - , Char. , fromEnum ... , , !

No instance for (Enum a0) arising from a use of ‘fromEnum’
The type variable ‘a0’ is ambiguous
Note: there are several potential instances:
  instance Integral a => Enum (GHC.Real.Ratio a)
    -- Defined in ‘GHC.Real’
  instance Enum Ordering -- Defined in ‘GHC.Enum’
  instance Enum Integer -- Defined in ‘GHC.Enum’
  ...plus 7 others
In the first argument of ‘(.)’, namely ‘fromEnum’
In the expression: fromEnum . toEnum
In an equation for ‘f’: f = fromEnum . toEnum

Haskell , , fromIntegral . round Integer. ByteString , , responseBody, , CHA.ByteString, , .

+6

x :: T x T

, . :

main = print . show . read $ "1234"

, , read .

, , . :

1 :: Int

, , .

+4

Source: https://habr.com/ru/post/1661989/


All Articles