Kyrill96
Kyrill96

Reputation: 39

Why is this Haskell array-code not working?

I have tried this code in Haskell :

array :: (Ix a) => (a,a) -> [(a,b)] -> Array a b
squares = array (1,100) [(i, i*i) | i <- [1..100]]

But when i run that Code i get this message by GHCi:

The type signature for array lacks an accompanying binding
      (The type signature must be given where array is declared)

What exactly is meant with accompanying binding and how to fix that?

Upvotes: 0

Views: 139

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477686

Because you define a type signature for array, not squares (array is a library function, you cannot redefine it, you can of course write your own). Now the compiler thinks you aim to define your own array and says: "Got that, but where is your function definition?" it thus lacks a binding (implementation so to speak).

The binding is thus its implementation (here squares = array (1,100) [(i, i*i) | i <- [1..100]]). Furthermore between brackets the compiler also says that you cannot define the function where you want, it must be in the file where the function signature is (the signature is where you define its type so :: (Ix a) => (a,a) -> [(a,b)] -> Array a b).

Given you meant to give a signature to squares, the type signature is too broad. The most generic type signature is:

squares :: (Enum e, Num e, Ix e) => Array e e
squares = array (1,100) [(i, i*i) | i <- [1..100]]

Upvotes: 3

Related Questions