Write insert and member operations in Haskell. Make sure that in ML and Haskell your Set data type is distinct from a list. In Haskell, define your Set type to be an instance of classes Eq and Show.
let setAdd l n = if (elem l n) then l else l ++ [n]
let setMember l i = l !! i
The code I written above just makes it have functions that perform on lists.
Is there a way to make this into a class? Sorry, I'm just learning functional programming. Is there a way to actually make a Set class that has member variables with such as a list?
Your data type here is [a]
, which already has such instances available, including Eq
and Show
(that by the way do the right thing).
If you want to have write your own instances, you should newtype
the underlying type, in a fashion similar to:
newtype Set a = Set { getSet :: [a] }
Then you can write:
instance Show a => Show (Set a) where
show (Set a) = ...
instance Eq a => Eq (Set a) where
Set a == Set b = ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.