In GHCi, I can do following:
ghci> let ddd n = [0..n]
ghci> ddd 10
[0,1,2,3,4,5,6,7,8,9,10]
However, if I define similar function in a file as :
ddd :: Int -> [a]
ddd n = [0..n]
After loading the file in GHCi, I got following error
ghci> :l dsp.hs
[1 of 1] Compiling Main ( dsp.hs, interpreted )
dsp.hs:43:13:
Couldn't match expected type `a' with actual type `Int'
`a' is a rigid type variable bound by
the type signature for ddd :: Int -> [a] at dsp.hs:42:8
In the expression: n
In the expression: [0 .. n]
In an equation for `ddd': ddd n = [0 .. n]
Failed, modules loaded: none.
Any reason??
Thanks
That's because you are returning a list of [a]
and not [Int]
, this should work:
ddd :: Int -> [Int]
ddd n = [0..n]
Or if you want a more generic solution:
ddd :: (Num a, Enum a) => a -> [a]
ddd n = [0..n]
If we enable the ExplicitForAll
extension, we can see that the type signature you gave is the same as
ddd :: forall a. Int -> [a]
The forall
is implied if it isn't written out, but the ExplicitForAll
extension makes it, well, explicit.
But, this isn't the case! Your definition doesn't work for all types a
, just for one specific type: Int
. So the correct signature is Int -> [Int]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.