[Haskell-cafe] Stack ADT?

Andrew Wagner wagner.andrew at gmail.com
Fri Feb 5 11:00:50 EST 2010


What's "going on" is that data structures in Haskell are immutable. Thus,
when you call "push" on a stack, you get a new stack with the new element
pushed onto it, and the original stack is left un-touched.

On Fri, Feb 5, 2010 at 10:56 AM, michael rice <nowgate at yahoo.com> wrote:

> Not using Stack for anything, just trying to understand how things can be
> done in Haskell.
>
> To that end...
>
> What's going on here? I'm not even calling function POP.
>
> Michael
>
> ======================
>
> module Data.Stack (Stack, emptyStack, isEmptyStack, push, pop, top) where
>
> newtype Stack a = Stack [a]
>
> emptyStack = Stack []
> isEmptyStack (Stack xs) = null xs
> push x (Stack xs) = Stack (x:xs)
> pop (Stack (_:xs)) = Stack xs
> top (Stack (x:_)) = x
>
> ======================
>
> [michael at localhost ~]$ ghci Stack.hs
> GHCi, version 6.10.4: http://www.haskell.org/ghc/  :? for help
> Loading package ghc-prim ... linking ... done.
> Loading package integer ... linking ... done.
> Loading package base ... linking ... done.
> [1 of 1] Compiling Data.Stack       ( Stack.hs, interpreted )
> Ok, modules loaded: Data.Stack.
> *Data.Stack> let s1 = emptyStack
> *Data.Stack> top (push 1 s1)
> 1
> *Data.Stack> top (push 2 s1)
> 2
> *Data.Stack> top (push 3 s1)
> 3
> *Data.Stack> let s2 = pop s1
> *Data.Stack> top s2
> *** Exception: Stack.hs:8:0-28: Non-exhaustive patterns in function pop
>
> *Data.Stack>
>
>
>
>
> --- On *Fri, 2/5/10, Casey Hawthorne <caseyh at istar.ca>* wrote:
>
>
> From: Casey Hawthorne <caseyh at istar.ca>
> Subject: Re: [Haskell-cafe] Stack ADT?
> To: haskell-cafe at haskell.org
> Date: Friday, February 5, 2010, 10:36 AM
>
> You could also implement stacks with mutable data structures, e.g.
> STArray, etc.
>
> What do you want to use a stack ADT for?
>
> Usually stacks are discussed for pedagogical purposes but usually
> recursion is used if you need a stack like operation.
> --
> Regards,
> Casey
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org <http://mc/compose?to=Haskell-Cafe@haskell.org>
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20100205/8de129da/attachment.html


More information about the Haskell-Cafe mailing list