Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell- Pattern syntax in expression context: _

Tags:

syntax

haskell

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?

like image 413
Andariel Avatar asked May 22 '12 08:05

Andariel


People also ask

What is a pattern in Haskell?

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.

How does pattern matching work in Haskell?

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.

What are view 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.


1 Answers

_ 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)
like image 189
Cat Plus Plus Avatar answered Sep 20 '22 02:09

Cat Plus Plus