无法弄清楚这种类型的错误

时间:2015-12-08 05:07:08

标签: haskell typeerror

我仍然对Haskell缺乏经验。话虽这么说,我很难找到编译器在我的代码Maybe (Maybe Int) -> Maybe Int中找到的这种类型的位置。据我所知,唯一应该返回的是Int值。

findThisPrime :: Int -> Int
findThisPrime num = calcPrime 1 num
    where calcPrime :: Int -> Int -> Int
          calcPrime curr 0 = curr
          calcPrime curr num = calcPrime (findPrime curr) (num - 1)
          findPrime :: Int -> Int
          findPrime here = (fromMaybe $ find (\x -> isPrime x) [here..])

错误:

hs> :l projectEuler
[1 of 1] Compiling Main             ( projectEuler.hs, interpreted )

projectEuler.hs:48:33:
    Couldn't match expected type `Int'
            with actual type `Maybe (Maybe Int) -> Maybe Int'
    In the expression: (fromMaybe $ find (\ x -> isPrime x) [here .. ])
    In an equation for `findPrime':
        findPrime here = (fromMaybe $ find (\ x -> isPrime x) [here .. ])
    In an equation for `findThisPrime':
        findThisPrime num
          = calcPrime 1 num
          where
              calcPrime :: Int -> Int -> Int
              calcPrime curr 0 = curr
              calcPrime curr num = calcPrime (findPrime curr) (num - 1)
              findPrime :: Int -> Int
              findPrime here = (fromMaybe $ find (\ x -> isPrime x) [here .. ])
Failed, modules loaded: none.

isPrime是一个函数,它接受一个I​​nt,检查它是否为素数,并返回一个Bool。

1 个答案:

答案 0 :(得分:4)

如果提供的<ipython-input-65-33285fd2319d> in f(x, y, spline) 29 if ndim == 0: result = spline(x,y)[0][0] 30 elif ndim == 1: ---> 31 result = spline(x,y).diagonal() 32 else: 33 result = spline(x.flatten(),y.flatten()).diagonal().reshape(x.shape) /usr/local/lib/python2.7/site-packages/scipy/interpolate/fitpack2.pyc in __call__(self, x, y, mth, dx, dy, grid) 826 z,ier = dfitpack.bispev(tx,ty,c,kx,ky,x,y) 827 if not ier == 0: --> 828 raise ValueError("Error code returned by bispev: %s" % ier) 829 else: 830 # standard Numpy broadcasting ValueError: Error code returned by bispev: 10 fromMaybe,则

Maybe a需要一个回落值:

Nothing

fromMaybe :: a -> Maybe a -> a fromMaybe _ (Just x) = x fromMaybe a Nothing = a 中,你错过了第一个参数,从而以错误的类型结束:

findPrime

我们可以查看类型以验证这实际上是错误:

findPrime here = (fromMaybe $ find (\x -> isPrime x) [here..])
              -- ^^^^^^^^^^^^^^^^^

这正是您看到的错误类型。

快速解决方案

如果您确定 find (\x -> isPrime x) [here..] :: Maybe Int fromMaybe :: a -> Maybe a -> a fromMaybe (find (\x -> isPrime x) [here..]) :: -> Maybe (Maybe Int) -> Maybe Int 始终返回find,则可以使用Just x。请注意,fromJust是部分的,如果您在fromJust上使用它,则会引发异常。

请注意,NothingfromJust $ find p xs相同,不需要额外的导入。