Write a recursive function that builds a set

I'm in trouble with one of my problems.

Write a recursive function that builds a set
mkSet :: Eq a => [a] −> Set a

One of the intended values ​​- I have to use another function called isElement

to check each value for duplicates. This is what I have forisElement

isElement :: Eq a => a -> [a] -> Bool
isElement x [] = False
isElement x (y:xs) = if x == y then True else isElement x xs

      

One of the main errors I usually get is every time I call isElement

, the value from is mkSet

returned as Bool (which I'm not sure how I do this).

This is what I have for mine mkSet

currently (also keep in mind that I am just starting to learn Haskell)

mkSet :: Eq a => [a] -> Set a
mkSet x [] = isElement x (xs)

      

What should I do?

Thank!

+3


source to share


1 answer


First of all, I think you are mkSet (x:xs)

instead mkSet x []

, because you are using xs.

Your function "mkSet x [] = isElement x (xs)" calls a function isElement

that returns instead Bool

. So what you are assigning nkSet x []

is Bool

not a Set a

.

so you want something like this:



mkSet' :: [a] -> [a]
mkSet' [] = []
mkSet' (x:[]) = [x]
mkSet' (x:xs) = if (isElement x xs) then (mkSet' xs) else (x:(mkSet' xs))

      

This function gives you a list with unique items. The only thing you need to know is to turn it into a set.

+2


source







All Articles