Data.Bits中的Haskell按位运算符

pu2*_*ppy 1 haskell bit-manipulation

我是Haskell的新手,我正在尝试使用Data.Bits中的按位操作.每次我尝试时都会收到错误消息

Prelude Data.Bits> 1 `shiftL` 16

<interactive>:1:0:
    Ambiguous type variable `t' in the constraint:
      `Bits t' arising from a use of `shiftL' at <interactive>:1:0-12
    Probable fix: add a type signature that fixes these type variable(s)
Run Code Online (Sandbox Code Playgroud)

对于许多操作都会发生这种情况,我也试过了.和.&.

我必须错过一些非常简单的事情,如果你能发现问题,请告诉我

zda*_*dav 8

在交互式会话中,Haskell无法推断出1和16的类型.然后,解决方案是给出一个提示:

> :m +Data.Bits
> let a = 1 :: Int
> let b = 16 :: Int
> a `shiftL` b
65535
>
Run Code Online (Sandbox Code Playgroud)

  • **可以*推断16的类型,因为`shiftL :: Bits a => a - > Int - > a`.只有1是模棱两可的. (4认同)