Elements of a List are all the same

Asked

Viewed 366 times

2

I made this function definition equal, which checks that all elements in a list are equal.

iguais :: [Float] -> Bool

iguais [x,y] = x == y  

iguais (h:t) = h == (head t) 

However the result is not the desired one. You can tell which is the error ?

  • That’s right @Carlosheuberger

2 answers

1

Your code does not work because you are not recursively comparing all elements.

Try this version here:

iguais :: [Float] -> Bool
iguais [] = True
iguais [_] = True
iguais (x:xs) = x == (head xs) && iguais xs -- chamada recursiva nesta linha
  • 1

    Instead of creating the constructor (x:tail) better use (x:xs) for tail is already a function that returns the remaining elements of the list and this can generate conflicts. The line would be: iguais (x:xs) = x == (head xs) && iguais xs

1

There is no recursion in his code, IE, he has to repeat this same operation for all elements of the list. An example of simple code would be this:

iguais :: [Float] -> Bool
iguais [] = False  
iguais (h:t) = elem h t || iguais t

This is the function elem:

elem :: Eq a => a -> [a] -> Bool
elem x [] = False
elem x (h:t) = if x == h then True else elem x t

Browser other questions tagged

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