Positioning an element in the list

2

Well, I had to do a function that, given a list and a number, returns the list element 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 given number is greater than the existing positions.

I have tried a where but it gives error. Can I put this where ? If, 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'

    
asked by anonymous 07.10.2017 / 22:25

1 answer

0

I made a small code that suits your purposes, 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)

Finds gets a list x and an integer value y. We use Guards to do a flow control that reads as follows:

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

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

No need to reinvent the wheel

There is an operator that does this, !! . To use it do the following:

[1,2,3,4]!!1 -- 2
    
08.10.2017 / 16:42