代码之家  ›  专栏  ›  技术社区  ›  RCIX

Haskell-更多类型推理问题

  •  1
  • RCIX  · 技术社区  · 15 年前

    getCount :: (Num a) => a -> [a]
    getCount int = foldl 
           processOneCount 
           [0,0,0,0,0,0,0,0,0,0] 
           (map (singleDigitCount) (map (digitToInt) (show int)))
    

    Couldn't match expected type `a' against inferred type `Int'
      `a' is a rigid type variable bound by
          the type signature for `getCount'
            at C:\Users\RCIX\Desktop\Haskell Code\test.hs:23:17
      Expected type: [a]
      Inferred type: [Int]
    In the expression:
        foldl
          processOneCount
          [0, 0, 0, 0, ....]
          (map (singleDigitCount) (map (digitToInt) (show int)))
    In the definition of `getCount':
        getCount int
                   = foldl
                       processOneCount
                       [0, 0, 0, ....]
                       (map (singleDigitCount) (map (digitToInt) (show int)))
    

    然而当我做一个 :t [0,0,0,0,0,0,0,0,0,0] 我回来了 [0,0,0,0,0,0,0,0,0,0] :: (Num t) => [t]

    2 回复  |  直到 15 年前
        1
  •  4
  •   Chuck    15 年前

    你正在使用 digitToInt

        2
  •  0
  •   Dan    15 年前

    恰克是对的。为了避免代码混乱,可以使用 . 操作员添加所需的功能:

      (map (singleDigitCount) (map (fromIntegral . digitToInt) (show int)))
    

    singleDigitCount processOneCount 还可以处理任意数字类型。