Haskell - Create Set (unique sorted list) - no recursion, no noob

Is it possible to create a function that will create a set with a list entry.

I just can't think of anything without using recursion.

I can use higher order functions like fold, filter, map, zip. I just can't have recursion in my function.

Obviously, I cannot use nub.

I hit my head trying to figure out how to get rid of duplicates without recursion or any type of loop (at least I don't think we can use loops, ask).

+3
source share
3 answers

One way to do this:

  • Sort list.
  • (, , [1,1,2,3] [(1,1),(1,2),(2,3)])
  • , .
  • , , zipped.

:

import Data.List

setify [] = []
setify xs = x : map snd (filter (uncurry (/=)) (zip sxs (tail sxs)))
    where sxs = sort xs
          x   = head sxs
+10

, , .

setify :: (Eq b) => [b] -> [b]
setify = foldl f []
where f acc next | next `elem` acc = acc 
                 | otherwise       = next:acc

, .

+4

Why are all complicated (and wrong!) Decisions? Just do the following:

uniq [] = []
uniq (x:xs)= x:(uniq (filter (/=x) xs))

setify xs = uniq $ sort xs -- If you want to sort too.

It filters each item from the tail of the list. Plain.

-2
source

Source: https://habr.com/ru/post/1766578/


All Articles