5
votes

I have been learning some Haskell and writing very simple programs. I want to make a function that will return the element at the given position. Here's what I tried to do-

elempos::Int->[a]->a
elempos n (b:_)=head (drop n (b:_) )

But I'm getting this error when I load the Test.hs file in the GHCi editor.

Pattern syntax in expression context: _

And it says Failed, modules loaded:none. Since I'm very new to the language I don't really have a proper idea what the mistake is(currently at chapter 4 of learn you a haskell). Can anyone tell me what is wrong here?

1
_ as pattern means "I don't care what it is", so it is not only not allowed, but makes no sense to "feed" it to a function like drop (which needs to know its arguments).Landei
There is !! operator doing what you need.demi

1 Answers

11
votes

_ is valid only inside patterns, you're trying to use it inside an expression: head (drop n (b : _)). Since you don't really need to decompose the list, and you do need the tail, the solution is to do:

elempos n xs = head (drop n xs)