簡體   English   中英

Haskell中的冪函數:(Floating Int)的實例均不因使用**而引起

[英]Power Function in Haskell: No instance for (Floating Int) arising from a use of `**'

我有以下功能:

probIndex idx xs = 
  xs!!idx+mult
  where mult = round(2**idx)

當我嘗試在ghci中加載它時,顯示以下錯誤:

Prelude> :load bn.hs
[1 of 1] Compiling Main             ( bn.hs, interpreted )

bn.hs:31:16:
    No instance for (RealFrac Int)
      arising from a use of `round'
    Possible fix: add an instance declaration for (RealFrac Int)
    In the expression: round (2 ** idx)
    In an equation for `mult': mult = round (2 ** idx)
    In an equation for `probIndex':
        probIndex idx xs
          = xs !! idx + mult
          where
              mult = round (2 ** idx)

bn.hs:31:23:
    No instance for (Floating Int)
      arising from a use of `**'
    Possible fix: add an instance declaration for (Floating Int)
    In the first argument of `round', namely `(2 ** idx)'
    In the expression: round (2 ** idx)
    In an equation for `mult': mult = round (2 ** idx)
Failed, modules loaded: none.
Prelude> 

為什么會發生? 2**idx返回float,但是round將其轉換為整數,因此一切都是整數。 那些“ Floating ”和“ RealFrac ”來自RealFrac

(**)是浮點數的冪函數。 對於整數,應使用整數冪(^)

probIndex idx xs = 
  xs!!idx + 2^idx

表達式xs!!idx+mult解析為

(xs !! idx) + mult

(!!)的類型是

>> :t (!!)
(!!) :: [a] -> Int -> a

這意味着idx :: Int 現在你有

>>> mult = round (2 ** idx)

並且(**)的類型是

>>> :t (**)
(**) :: Floating a => a -> a -> a

由於idx :: Int您可以專門研究(**) :: Floating Int => Int -> Int -> Int ,這是您遇到問題的地方Int不是Floating的實例。 為了解決這個問題,您可以改寫

>>> mult = round (2 ** fromIntegral idx)

這會將idx強制轉換為小數類型,並滿足類型檢查器的要求。 或者,如果原始表達式的解析不是您想要的,則只需將其替換為

xs !! (idx + mult) where mult = ...

並且您的代碼應正確鍵入check。

您的代碼被解析為

probIndex idx xs = (xs !! idx) + mult
  where mult = round (2**idx)

現在,

Prelude> :t (**)
(**) :: (Floating a) => a -> a -> a

這使其成為idx :: (Floating a) => a ,但是

Prelude> :t (!!)
(!!) :: [a] -> Int -> a

這使其成為idx :: Int 因此,未成功嘗試找到(Floating Int)實例。 與來自round :: (RealFrac a, Integral b) => a -> b RealFrac類似。

無恥的插件:您可以在此答案中找到更多有關類型派生的信息:))。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM