Position of an element in the list

Asked

Viewed 918 times

1

Well, I had to do a function that, given a list and a number, returns the element from the list that is in that position (the number).

Basically it is the function already defined. The problem is that I have to restrict the function in case the number given is higher than the existing positions.

I tried for a where but it gives error. I can put this where? If not, in what situations can I use where?

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

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

of this error: parse error on input `Where'

  • what would be this function that is already defined?

1 answer

0

I made a little code that fits your purpose, see:

localiza :: [a] -> Int -> a
localiza x y
    | y > length x - 1 = error "Posição excede o tamanho da lista"
    | otherwise = head(drop y x)

main = do 
    let list = [1,2,3,4]
    print $ list -- Imprime a lista 
    print $ localiza list 3 -- Imprime o 4° elemento 0-index
    print $ list -- Imprime novamente a lista

Explaining the code

localiza x y
    | y > length x = error "Posição excede o tamanho da lista"
    | otherwise = head(drop y x)

Locates a list x and an integer y value. We use Guards to do a flow control that says the following:

  • If y is larger than the list size returns an error
  • Otherwise return the first element of the list with y less positions (the original list is not changed)

In the code main i assign a value to the variable list using the keyword Let, I use the location function and then print the list again only to show that it has not been changed.

No need to reinvent the wheel

There’s an operator who does this, the !!. To use it do the following:

[1,2,3,4]!!1 -- 2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.