Haskell无法匹配类型

时间:2015-11-27 19:27:13

标签: haskell

我仍然是Haskell的初学者,我有这段代码,但ghc不编译并给我一个错误

这是代码:

data QT a = C a | Q (QT a) (QT a) (QT a) (QT a) deriving (Show)

moltiply :: QT a -> Int -> QT a
moltiply (C a) x = (C (a * x))
moltiply (Q a b c d) x = Q (moltiply a x) (moltiply b x) (moltiply c x) (moltiply d x)

这是我得到的错误:

Couldn't match expected type ‘a’ with actual type ‘Int’
      ‘a’ is a rigid type variable bound by
          the type signature for multiply :: QT a -> Int -> QT a
          at file.hs:12:15
    Relevant bindings include
      a :: a (bound at file.hs:13:15)
      multiply :: QT a -> Int -> QT a
        (bound at file.hs:13:1)
    In the second argument of ‘(*)’, namely ‘x’
    In the first argument of ‘C’, namely ‘(a * x)’

2 个答案:

答案 0 :(得分:8)

写作时

a

您告诉GHC此功能适用于QT类型中的任何类型moltiply (C a) x = (C (a * x)) ,但您写了

a

并尝试将值Int乘以moltiply的任意类型。这似乎不对吗?

您可以通过两种方式解决此问题:

  1. 通过删除类型签名并在GHCi中加载文件,向GHCi询问最常见的λ> :t moltiply moltiply :: Num a => QT a -> a -> QT a 类型:

    Int

    然后,您可以将此类型签名添加到源文件(适用于文档)或保留没有类型签名的函数。

  2. 坚持moltiplyQT要求Int包含moltiply :: QT Int -> Int -> QT Int

    it('should return movie data from search query', function () {
      var response;
    
      $httpBackend.whenJSONP('http://api.themoviedb.org/3/search/movie?api_key=a8f7039633f2065942cd8a28d7cadad4&query=james%20spectre&callback=JSON_CALLBACK')
        .respond(200, movieData);
    
      MovieSearch.search('james spectre')
        .then(function(data){
          response = data;
    
          expect(response).toEqual(movieData);
        });
    
    
      $httpBackend.flush();
    
    })
    

答案 1 :(得分:2)

使用Int *可以乘以Int的另一个moltiply :: QT Int -> Int -> QT Int 。您需要将类型签名限制为

moltiply :: Num a => QT a -> a -> QT a

或将其概括为

moltiply :: (Num a, Integral b) => QT a -> b -> QT a
moltiply (C a) x = (C (a * fromIntegral x))
moltiply (Q a b c d) x = Q (moltiply a x) (moltiply b x) (moltiply c x) (moltiply d x)

或将实现更改为

error:
 *** SQLException caught ***
ORA-28040: No matching authentication protocol