My aim is to list all elements of the array a whose values are greater than their index positions. I wrote a Haskell code like this.
[a|i<-[0..2],a<-[1..3],a!!i>i]
When tested on ghci prelude prompt, I get the following error message which I am unable to understand.
No instance for (Num [a]) arising from the literal 3 at <interactive>:1:20 Possible fix: add an instance declaration for (Num [a])
Given the expression
a!!i, Haskell will infer thatais a list (i.e.a::[a]). Given the expressiona<-[1..3], Haskell will infer thatawill have typeNum a => a(because you are drawingafrom a list ofNum a => avalues). Trying to unify these types, Haskell concludes thatamust actually be of typeNum a => [a].The bottom line is that it doesn’t make sense to treat
aas a list in one context and as an element from a list of numbers in another context.EDIT
I’m thinking you could do what you want with something like this:
The expression
xs `zip` [0..]creates a list of pairs, where the first value in each pair is drawn fromxsand the second value from[0..](an infinite list starting from 0). This serves to associate an index to each value inxs. The expressionuncurry (>)converts the<operator into a function that works on pairs. So the expressionfilter (uncurry (>))filters a list of pairs to only those elements where the first value is greater than the second. Finally,map fstapplies thefstfunction to each pair of values and returns the result as a list (thefstfunction returns the first value of a pair).EDIT 2
Writing pointless code is fun, and so I give you: