Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Correctly use Multiple Parameters

Tags:

haskell

I am trying to make my own "Set" datatype and when I try to declare an insert function the compiler complains about too few arguments:

quantities.hs:12:27:
Expecting one more argument to `Set'
In the type signature for `insert': insert :: Set e -> Int -> Set

How can I correctly define the insert function to add a new element to my set?

Here is what I have so far:

data Set e = Set [e]

mySet :: Set Int
mySet = Set [1, 2, 3, 4, 5]

setLength :: Set e -> Int
setLength (Set s) = length s

empty :: Set e -> Bool
empty (Set s) = if null s then True else False

insert :: Set e -> Int -> Set
insert set value = set : value

main = do print(insert mySet 1)
like image 225
Samuel Barnes Avatar asked May 30 '26 00:05

Samuel Barnes


1 Answers

You have to implement insert like as follows. Note that your type signature isn't correct. You cannot insert Int to a set of type Set e (you can only insert Int to a set of type Set Int).

insert :: Set e -> e -> Set e
insert (Set s) value = Set $ value : s

Note that the above insert doesn't take into account of duplicate elements(Hint: use nub for eliminating that).

like image 106
Sibi Avatar answered Jun 01 '26 17:06

Sibi