Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

[Haskell] Custom stack-push function for haskell

haskell push stack

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1 jasonalien


    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 194 posts

Posted 02 March 2013 - 02:01 PM

Hello, I want to make a push function for this stack data type :


data Stack = Empty | Elem Char Stack deriving Show

What I have done so far is this :


push :: Char -> Stack ->Stack
push  x Empty = (Elem x Empty)
push   x  (Elem stack Empty) = (Elem x (Elem stack Empty) )

When I give this input :

push 'g' (Elem 'a' Empty)


it gives this :


Elem 'g' (Elem 'a' Empty)


But I want my function to give this :


Elem 'g' (Elem 'a' Empty)


For this input :

push 'g' Elem 'a' Empty


Can you help me how I can do that? Thanks.

#2 sepp2k


    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 183 posts

Posted 03 March 2013 - 10:47 PM

If I understood you correctly, you want to be able to leave out the parens when calling push. You can't do that. push 'g' Elem 'a' Empty will call push with 4 arguments, but push takes only two arguments, so that can't work. It is not possible to define a function that takes arbitrarily many arguments in Haskell (at least not in any useful way).

You can write push 'g' $ Elem 'a', using $ instead of parentheses, but you can't just leave the parens off without replacing them with anything.

PS: You might already be aware of this, but your push function, as it is currently defined, will only work if its second argument is either empty or contains a single element. You might want to formulate your definition of push in a way that doesn't hardcode the size of the stack. Note that the size of the stack shouldn't affect at all what you need to do to push into it - it shouldn't even matter whether it's empty or not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download