开发者

Haskell function signature and "Could not deduce" compiler error

开发者 https://www.devze.com 2023-02-20 09:53 出处:网络
I\'m writing a Haskell library which uses Data.Vector\'s. I successfully wrote library function, but I don\'t know how to add signature to it. Below is a simple example illustrating the problem:

I'm writing a Haskell library which uses Data.Vector's. I successfully wrote library function, but I don't know how to add signature to it. Below is a simple example illustrating the problem:

import qualified Data.Vector.Generic as V

-- zip two vectors and return first element as a tuple
test :: (V.Vector v a, Fractional a) => v a -> v a -> (a, a)
test a b = (V.zip a b) V.! 0

This code causes following compilation error:

Could not deduce (V.Vector v (a, a))
  from the context (V.Vector v a, Fractional a)
  arising from a use of `V.zip' at MyLib.hs:7:12-20
Possible fix:
  add (V.Vector v (a, a)) to the context of
    the type signature for `test'
  or add an instance declaration for (V.Vector v (a, a))
In the first argument of `(V.!)', namely `(V.zip a b)'
In the expression: (V.zip a b) V.! 0
In the definition of `test': test a b = (V.zip a b) V.! 0

Code is compl开发者_JAVA百科ied if I comment out the signature of test function. What is a correct signature here?

I'm using GHC 6.12.3, vector library 0.7.0.1.

Thanks.


ghci says:

Prelude Data.Vector.Generic> :t \a b -> (Data.Vector.Generic.zip a b) Data.Vector.Generic.! 0
\a b -> (Data.Vector.Generic.zip a b) Data.Vector.Generic.! 0
  :: (Vector v a, Vector v b, Vector v (a, b)) =>
     v a -> v b -> (a, b)

Matching with your case, the signature should be

test :: (V.Vector v a, Fractional a, V.Vector v (a, a)) => v a -> v a -> (a, a)

(oh and you need FlexibleContexts)

0

精彩评论

暂无评论...
验证码 换一张
取 消