首页 > 解决方案 > 函数在应用程序中产生“类型错误”消息(Haskell)

问题描述

我正在编写这个函数,旨在计算缓存索引所需的位数。它使用如下所示的公式和类型。

问题是它会产生以下错误消息。我怎样才能解决这个问题 ?

源代码:

getNumBits :: (Integral a, RealFloat a1) => a1 -> [Char] -> [c] -> a
getNumBits fromIntegral(numOfSets) cacheType (x:xs)
  | (cacheType=="fullyAssoc") = 0
  | (cacheType=="setAssoc")   = fromIntegral(logBase2(fromIntegral(length (x:xs)))/numOfSets)
  | (cacheType=="directMap")  = fromIntegral(logBase2(fromIntegral(length (x:xs))))

错误信息:

ERROR file:.\HaskellProject.hs:27 - Type error in application
*** Expression     : fromIntegral (logBase2 (fromIntegral (length (x : xs))) / numOfSets)
*** Term           : logBase2 (fromIntegral (length (x : xs))) / numOfSets
*** Type           : [Char]
*** Does not match : Int

标签: haskell

解决方案


getNumBits fromIntegral(numOfSets) cacheType (x:xs)

这不是haskell,你从哪里学来的?您不能以这种方式将函数应用于参数。相反,将参数绑定到变量并在正文或where子句中应用函数:

getNumBits numOfSetsFloat cacheType (x:xs)
 ...
 where numOfSets = fromIntegral numOfSetsFloat

此外,您还需要处理最后一个参数的空列表案例,否则当有人将函数调用为getNumBits 0 [] [].


推荐阅读