且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

指数默认为整数

更新时间:2023-11-30 16:32:10

你可以用更具体的类型定义你自己的操作符。或者你可以使用更具体的类型来重新定义(^)运算符,如下所示:

  $ b $(^):: Num a => code> import Prelude hiding((^))
import qualified Prelude a - > Int - > a
(^)=(Prelude。^)

x :: Int
x = 2 ^ 3


I use (^) :: (Num a, Integral b) => a -> b -> a a lot to define constant factors or sizes. Problem is that GHC complains about defaulting to Integer.

Now I know why this happens ... and I know that I can "just" write (x^(y::Int)) to get rid of the warning. But that looks just "ugly". Otoh living with the warnings is also not a great option.

Same thing applies for (^^) :: (Integral b, Fractional a) => a -> b -> a and (**) :: Floating a => a -> a -> a is not usable to me.

Anyone has a nice solution to this (first world) problem?

edit

Just found this gem of code:

alignment a = 2 ^ ceiling (logBase 2 (fromIntegral (sizeOf a)))

This is one LOC and GHC complains about defaulting to Integer and Double on the same line.

You could define your own operator with a more specific type. Or you could redefine the (^) operator with a more specific type, like this:

import Prelude hiding ((^))
import qualified Prelude ((^))

(^) :: Num a => a -> Int -> a
(^) = (Prelude.^)

x :: Int
x = 2^3