如何在Haskell中进行类型转换?

Ala*_*ius 5 haskell type-conversion

我在文件main.hs中有以下代码:

teste :: Integral a => a -> a
teste n = truncate (sqrt n) + mod n 2
Run Code Online (Sandbox Code Playgroud)

当我尝试加载它时,我从ghci中收到以下错误:

Prelude> :l main.hs 
[1 of 1] Compiling Main             ( main.hs, interpreted )

main.hs:12:11:
    Could not deduce (RealFrac a) arising from a use of ‘truncate’
    from the context (Integral a)
      bound by the type signature for teste :: Integral a => a -> a
      at main.hs:11:10-29
    Possible fix:
      add (RealFrac a) to the context of
        the type signature for teste :: Integral a => a -> a
    In the first argument of ‘(+)’, namely ‘truncate (sqrt n)’
    In the expression: truncate (sqrt n) + mod n 2
    In an equation for ‘teste’: teste n = truncate (sqrt n) + mod n 2

main.hs:12:21:
    Could not deduce (Floating a) arising from a use of ‘sqrt’
    from the context (Integral a)
      bound by the type signature for teste :: Integral a => a -> a
      at main.hs:11:10-29
    Possible fix:
      add (Floating a) to the context of
        the type signature for teste :: Integral a => a -> a
    In the first argument of ‘truncate’, namely ‘(sqrt n)’
    In the first argument of ‘(+)’, namely ‘truncate (sqrt n)’
    In the expression: truncate (sqrt n) + mod n 2
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)

但是当我在交互模式下运行相同的代码时,它可以正常工作:

Prelude> truncate (sqrt 5) + mod 5 2
3
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 6

在您的通话中,的类型不同。的确,in中应具有as类型,而in中具有type 。尽管严格说来可以在Haskell中构造两个类型家族的成员,但是从概念上讲,一个类型既是and ,又很奇怪,它也仅适用于此类,这使它的用处不大。因此,我们可以将签名更改为:truncate (sqrt 5) + mod 5 255sqrt 5Floating a => a5mod 5 2Integral b => bIntegralFloating

teste :: (Integral a, Floating a, RealFrac a) => a -> a
teste n = truncate (sqrt n) + mod n 2
Run Code Online (Sandbox Code Playgroud)

但是正如前面所说,这不是很有用。

您可以使用fromIntegral :: (Integral a, Num b) => a -> b此处将Integral类型从任何Num类型转换为任何类型,例如:

teste :: Integral a => a -> a
teste n = truncate (sqrt (fromIntegral n)) + mod n 2
Run Code Online (Sandbox Code Playgroud)

例如:

Prelude> teste 5
3
Run Code Online (Sandbox Code Playgroud)