Function to determine if all elements are the same

945 views
Skip to first unread message

Juan Martin Buireo

unread,
Jun 18, 2016, 2:47:41 PM6/18/16
to Elm Discuss
Hi, I need to make a function and I am having some trouble.


In Haskell I know how to do it but here in Elm is differente due to the implementation of Lists.


I have a huge list and I want to check if all elements in the list are the same. I have a Haskell function that works but in Elm it doesn't because List.tail returns a Maybe (List a). So with this, i cannot do a List.map or List.all on the tail of the list.


Thanks

Peter Damoc

unread,
Jun 18, 2016, 3:07:02 PM6/18/16
to Elm Discuss
Here is one way to do it:

allTheSame xs  =
  case Set.toList(Set.fromList xs) of
    [] -> True -- or False, your choice 
    x::[] -> True 
    _ -> False


If you convert a list into a set, and the set back to a list, you will get a list with only one element for a list of identical elements 


here is another approach 

allTheSame2 xs = 
  let 
     check x rest =
       case rest of 
         [] -> True 
         y::ys -> x == y && check x ys
  in 
    case xs of 
      [] -> True -- or False 
      y::ys -> check y ys

and another approach

allTheSame3 xs = 
  let 
    f x acc = 
      if List.member x acc then acc else x::acc
  in 
    List.length (List.foldl f [] xs) <= 1  
 


--
You received this message because you are subscribed to the Google Groups "Elm Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elm-discuss...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
There is NO FATE, we are the creators.
blog: http://damoc.ro/

Peter Damoc

unread,
Jun 18, 2016, 3:09:53 PM6/18/16
to Elm Discuss
Actually, the most sensible would be:

allTheSame4 xs  =
  Set.size (Set.fromList xs) <=1
  


slosh...@gmail.com

unread,
Jun 18, 2016, 10:45:00 PM6/18/16
to Elm Discuss
Here's another way using List.all:

allTheSame xs =

  case xs of
    [] -> True
    y :: ys -> List.all ((==) y) ys
Reply all
Reply to author
Forward
0 new messages