Haskell类型错误?

时间:2017-07-02 15:32:03

标签: haskell

我对Haskell真的很陌生,它给了我很多时间。我试图写一个类似于&lnspace'的基本功能。在Matlab中,但编译器似乎拒绝了“地板”的想法。产生一个积分类型。我的代码:

linspace :: Double -> Double -> Double -> [Double]
linspace x dx y
    | y' == y   = [x + i * dx | i <- nums]
    | otherwise = ([x + i * dx | i <- nums] ++ [y])
    where
        n = floor ((y - x) / dx)
        nums = [0..n]
        y' = (x + (fromIntegral n) * dx)

在ghci中产生错误:

maths.hs:8:21: error:
    * No instance for (Integral Double) arising from a use of `floor'
    * In the expression: floor ((y - x) / dx)
      In an equation for `n': n = floor ((y - x) / dx)
      In an equation for `linspace':
          linspace x dx y
            | y' == y = [x + i * dx | i <- nums]
            | otherwise = ([x + i * dx | i <- nums] ++ [y])
            where
                n = floor ((y - x) / dx)
                nums = [0 .. n]
                y' = (x + (fromIntegral n) * dx)

maths.hs:10:28: error:
    * No instance for (Integral Double)
        arising from a use of `fromIntegral'
    * In the first argument of `(*)', namely `(fromIntegral n)'
      In the second argument of `(+)', namely `(fromIntegral n) * dx'
      In the expression: (x + (fromIntegral n) * dx)
Failed, modules loaded: none.

2 个答案:

答案 0 :(得分:5)

由于类型注释,您已将Incorrect decimal value: '' for column '' at row -1 的结果绑定为INSERT INTO DUMP (storename, balance, otherbalance) SELECT storename, IF(balance = '', 0.0, CAST(balance AS DECIMAL (9,2))) AS balance, '0.0' AS otherbalance FROM superchart AND storename IN ('Superstore') 。因此,linspace必须生成[Double] s这样的列表。 [x + i * dx | i <- nums]Double必然是x,因为它们是传递给函数的参数,它们都被声明为dx。但是Double呢?它来自Double;要inumsi必须为Double

Nums定义为

nums

好的,[Double]列表没问题。但是是什么的列表?这取决于nums = [0..n] ;我们来看看吧!

nums
简而言之,

n需要n = floor ((y - x) / dx) 并生成floor。因此,Double是积分列表。这是您获得的错误:Integral没有nums的实例;这些类型无法很好地解决问题。

要解决这些错误,您必须Integral Double

n

因此,您的Double定义也必须更改:

n = fromIntegral $ floor ((y - x) / dx)

简而言之

y'

答案 1 :(得分:3)

此版本编译:

linspace :: Double -> Double -> Double -> [Double]                                                                                                                   
linspace x dx y
    | y' == y   = [x + (fromIntegral i) * dx | i <- nums]
    | otherwise = ([x + (fromIntegral i) * dx | i <- nums] ++ [y])
    where
        n = toInteger $ floor ((y - x) / dx)
        nums = [0..n]
        y' = (x + (fromIntegral n) * dx)

有哪些变化?

  • 正如@Alec评论的那样,虽然floor 逻辑是一个整数,但它的类型却不是。您需要使用toInteger

  • 在此之后,您需要在fromIntegral和`dex。

  • 相乘时使用i