[Haskell-cafe] Re: iterative algorithms: how to do it in Haskell?

Lennart Augustsson lennart at augustsson.net
Mon Aug 21 08:33:06 EDT 2006


I don't know exactly what types you have as base types in your  
implementation, but here's a small code fragment that of what I had  
in mind.

data Value = D Double | S String | B Bool

type Stack = [Value]

-- Add top stack elements
plus :: Stack -> Stack
plus (D x : D y : vs) = D (x+y) : vs
plus (  _ :   _ :  _) = error "Bad operands to plus"
plus                _ = error "Not enough operands on stack"

equal :: Stack -> Stack
equal (D x : D y : vs) = B (x == y) : vs
equal (S x : S y : vs) = B (x == y) : vs
equal (B x : B y : vs) = B (x == y) : vs
equal (  _ :   _ :  _) = error "Bad operands to equal"
equal                _ = error "Not enough operands on stack"

	-- Lennart

On Aug 21, 2006, at 04:42 , Gene A wrote:

> Lennart and all,
>
> On 8/19/06, Lennart Augustsson <lennart at augustsson.net> wrote:
>> There are much better ways than storing strings on the stack.
>> Like using a data type with constructors for the different types that
>> you can store.
>>
>> 	-- Lennart
>
> Off topic, but .... this is important info for me!
> Okay then, by doing that you can define a new type that "encodes" the
> other types.. such that you can actually end up storing the different
> types such as Int, Integer,Real, String, etc into a list ..... using
> this new type to so that even though you are in effect storing
> differing types to a list.. they are actually of the same type and
> thus legal... without doing an explicit bunch of "read"/"show"
> combinations.. to actually convert.. .... like Num for example... and
> being able to use +,* on any of the numeric types... but can you have
> a list of type [Num] ?? I thought that it had to be the base types of
> Int, Integer, Float, Double  etc..  No?
>
> thanks,
> gene
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe



More information about the Haskell-Cafe mailing list