Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell set datatype/datastructure

What i want to do is to create a type Set in Haskell to represent a generic(polymorphic) set ex. {1,'x',"aasdf",Phi}

first i want to clear that in my program i want to consider Phi(Empty set) as something that belongs to all sets

here is my code

data Set a b= Phi | Cons a (Set a b)
deriving (Show,Eq,Ord)


isMember Phi _ = True
isMember _ Phi = False
isMember x (Cons a b) = if x==a
               then True
               else isMember x b

im facing a couple of problems:

  1. I want isMember type to be

    isMember :: Eq a => a -> Set a b -> Bool
    

    but according to my code it is

    isMember :: Eq a => Set a b -> Set (Set a b) c -> Bool
    
  2. If i have a set of different times the == operator doesn't work correctly so i need some help please :D

like image 337
blenddd Avatar asked Jul 07 '26 00:07

blenddd


1 Answers

Regarding your type error, the problem looks like the first clause to me:

isMember Phi _ = True

This is an odd clause to write, because Phi is an entire set, not a set element. Just deleting it should give you a function of the type you expect.

Observe that your Set type never makes use of its second type argument, so it could be written instead as

data Set a = Phi | Cons a (Set a)

...and at that point you should just use [a], since it's isomorphic and has a huge entourage of functions already written for using and abusing them.

Finally, you ask to be able to put things of different types in. The short answer is that Haskell doesn't really swing that way. It's all about knowing exactly what kind of type a thing is at compile time, which isn't really compatible with what you're suggesting. There are actually some ways to do this; however, I strongly recommend getting much more familiar with Haskell's particular brand of type bondage before trying to take the bonds off.

like image 121
Daniel Wagner Avatar answered Jul 08 '26 22:07

Daniel Wagner