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?
We use pattern matching in Haskell to simplify our codes by identifying specific types of expression. We can also use if-else as an alternative to pattern matching. Pattern matching can also be seen as a kind of dynamic polymorphism where, based on the parameter list, different methods can be executed.
Pattern matching consists of specifying patterns to which some data should conform and then checking to see if it does and deconstructing the data according to those patterns. When defining functions, you can define separate function bodies for different patterns.
View patterns are somewhat like pattern guards that can be nested inside of other patterns. They are a convenient way of pattern-matching against values of abstract types.
_
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With