Haskell 显式类型转换?

Haskell 显式类型转换?,haskell,types,Haskell,Types,这是一个示例函数: 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" le

这是一个示例函数:

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)

这是否明确说明类型必须是CHA.ByteString?或者它有其他作用吗?

符号
x::T
读取表达式x的类型为T

在存在类型类和更高级别的类型时,这可能是必要的,以使编译器能够对程序进行类型检查。例如:

main = print . show . read $ "1234"
是不明确的,因为编译器无法知道要使用哪个重载的
read
函数

此外,还可以缩小编译器推断的类型。例如:

1 :: Int

最后,像这样的类型签名通常用于使程序更具可读性

是的,这只是明确说明类型必须是
CHA.ByteString
。这本身不会引起任何类型的转换,只是提示编译器(和/或读者)
res
必须具有这种类型

当值是由具有多态结果的函数生成的,并且仅由具有多态参数的函数使用时,就需要这些类型的局部注释。一个简单的例子:

f :: Int -> Int
f = fromEnum . toEnum
这里,将整数转换为任意可枚举类型–例如可以是
Char
。无论您选择什么类型,
fromnum
都可以将其转换回。。。问题是,没有办法决定中间结果应该使用哪种类型

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。舍入
将自动使用
整数
。但是像
ByteString
这样的类型没有默认值,因此对于像这样的多态结果函数,您要么需要将结果传递给只能接受
CHA.ByteString
的单态函数,要么需要添加一个显式注释,说明这应该是该类型

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