[Haskell-cafe] Stack ADT?

minh thu noteed at gmail.com
Fri Feb 5 11:04:54 EST 2010


2010/2/5 michael rice <nowgate at yahoo.com>
>
> 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

When you write
  push 1 s1
you get a new stack value. you can view it by typing 'it' in ghci
(provided you have an instance of Show for it).

s1 is still s1, the empty stack.

When you write
  let s2 = pop s1
Nothing happens yet, but if you want to evaluate s2, e.g. by typing it
in ghci, pop will be applied to the empty stack, which is not taken
care of in its definition.
And you do want evaluate s2 when you eventually write
  top s2.

HTH,
Thu


More information about the Haskell-Cafe mailing list