Joao Parente
Joao Parente

Reputation: 453

Where can I use where?

Well, i had to do this function that, given a list and a number, it returns the element of the list in the position of number (being first position 0)

basically its the function (!!). The problem that I face is that I need to restrict to this function , case the position given is bigger than the positions in the list, i tried to use a when but it doesn't work, it shows this error:

parse error on input `where'

Can I use a where here? in which situations can i use a where?

localiza:: [a]->Int->a

localiza [a] 0 = a
localiza (a:as) b  = localiza (as) (b-1) 
                     where b+1 <= length(a)

Upvotes: 0

Views: 100

Answers (2)

Leif Metcalf
Leif Metcalf

Reputation: 3

I'm going to give this example from the Haskell wiki.

elementAt' (x:_) 1  = x
elementAt' [] _     = error "Index out of bounds"
elementAt' (_:xs) k
  | k < 1           = error "Index out of bounds"
  | otherwise       = elementAt' xs (k - 1)

This does not check the length so often, only exiting when the list becomes empty.

Upvotes: 0

sepp2k
sepp2k

Reputation: 370172

In Haskell where introduces a set of local definitions. It can be attached to any definition to define variables that are local to that definition. So the problem in your code is not where you use where, it's what you use it for.

You're not trying to define local variables, you're trying to add a condition to your pattern. For that you use pattern guards, which have the syntax pattern | boolean-condition, i.e. localiza (a:as) b | b < length as = ....

That said, this isn't really a good way to do this. length is an O(n) operation, so checking the length at each step of the iteration wastes a lot of time. Instead you could just catch the case when the list becomes empty, which will only happen if the index was out of bounds.

Upvotes: 3

Related Questions