Haskell错误中无法匹配预期的类型

时间:2019-05-23 16:00:19

标签: haskell

我在Haskell中的代码有问题。对于任务,我们的数据的日期类型为Int,温度度类型为Float。我必须定义一个函数来返回温度接近月平均温度的日期。这是我的代码:

data Measuring = Temp Int Float

temp :: Measuring -> Float
temp (Temp _ tem) = tem

date :: Measuring -> Int
date (Temp dat _) = dat

averageTemp :: [Measuring] -> Float
averageTemp lst = (foldr1 (+) (map temp lst)) / fromIntegral (length lst)

closestToAverage :: [Measuring] -> Int
closestToAverage lst = foldl1 (\ t1 t2 -> if abs(averageTemp lst - t1) <= 
abs(averageTemp lst - t2)
then date t1 else date t2) lst

错误

"* Couldn't match expected type `Int' with actual type `Float'
    * In the expression:
        foldl1
          (\ t1 t2
             -> if abs (averageTemp lst - t1) <= abs (averageTemp lst - t2) then
                    date t1
                else
                    date t2)
          lst
      In an equation for `closestToAverage':
          closestToAverage lst
            = foldl1
                (\ t1 t2
                   -> if abs (averageTemp lst - t1) <= abs (averageTemp lst - t2) then
                          date t1
                      else
                          date t2)
                lst
   |
83 | closestToAverage lst = foldl1 (\ t1 t2 -> if abs(averageTemp lst - t1) <= abs(averageTemp lst - t2)

   |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"

1 个答案:

答案 0 :(得分:3)

onCreate的类型为Observable.timer(1, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .doOnNext(time ->{ fetchAndActiveRemoteConfig(); }) .subscribe(); 。请注意,高阶函数必须具有与其两个输入类型相同的输出类型。因此,您需要返回foldl1Foldable t => (a -> a -> a) -> t a -> a,而不是t1t2

此外,由于date t1date t2的类型为t1,因此不能从t2中减去它们。您需要使用Measuring提取averageTemp lst值。

Float