[Haskell-cafe] Stack ADT?
nowgate at yahoo.com
Fri Feb 5 11:33:03 EST 2010
I see now that what I thought was happening wasn't happening at all.
> top (push 1 s1) gives me the top of the new Stack returned by PUSH. s1 remains unchanged.
--- On Fri, 2/5/10, minh thu <noteed at gmail.com> wrote:
From: minh thu <noteed at gmail.com>
Subject: Re: [Haskell-cafe] Stack ADT?
To: "michael rice" <nowgate at yahoo.com>
Cc: haskell-cafe at haskell.org, "Casey Hawthorne" <caseyh at istar.ca>
Date: Friday, February 5, 2010, 11:04 AM
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.
> 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)
> *Data.Stack> top (push 2 s1)
> *Data.Stack> top (push 3 s1)
> *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
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe