Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a recursive function that constructs a set

I'm having trouble with one of my hw problems.

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

One of the hints given is I should be using another function called isElement to check each value for duplicates. Here is what I have for isElement

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 tend to get is everytime I call isElement, the value from mkSet returns as a Bool (which I am not sure how I am doing).

This is what I have for my mkSet currently (also keep in mind I'm just starting to learn Haskell)

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

What is it that I should be doing?

Thanks!

like image 682
Hotaru009 Avatar asked Sep 20 '26 15:09

Hotaru009


1 Answers

First of all, I think you ment mkSet (x:xs) instead of mkSet x [], because you use the xs.

Your function 'mkSet x [] = isElement x (xs)' is calling the function isElement, which in his place returns a Bool. So what you are assigning to nkSet x [] is a Bool and no a Set a.

so what you do want is 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 elements. The only thing you have to do know is to turn it into a set.

like image 126
Kriptoniet Avatar answered Sep 22 '26 07:09

Kriptoniet