Re: Help needed with behaviour of SML..

igl@ecs.soton.ac.uk (Ian Glendinning)
29 Apr 91 14:20:47 GMT

          From comp.compilers

Related articles
Help needed with behaviour of SML.. surendar@enuxva.eas.asu.edu (Surendar Chandra) (1991-04-26)
Re: Help needed with behaviour of SML.. igl@ecs.soton.ac.uk (1991-04-29)
| List of all articles for this month |

Newsgroups: comp.compilers
From: igl@ecs.soton.ac.uk (Ian Glendinning)
Keywords: ML
Organization: University of Southampton, UK
References: <9104262025.AA21840@enuxva.eas.asu.edu>
Date: 29 Apr 91 14:20:47 GMT

In <9104262025.AA21840@enuxva.eas.asu.edu> surendar@enuxva.eas.asu.edu (Surendar Chandra) writes:


> I need some help with the behaviour of a SML system.. I am trying to
>implement a subset as part of my course project .


>The following code sequence behaves as following
>> val a = 1;
>> a ;
>| 1 : int ;
>> fun b c = c * a ;
>> b 2 ;
>| 2 : int ;
>> val a = 3;
>> b 2 ;
>| 2 : int ;
>^^^^^^^^^^
> Why does it do it like this.. Why doesn't it look up at the current


It behaves like this because 'a' is a constant value, not a variable.
Functional languages do not have any variables!


>value of the variable 'a'. Why does it store the current value of 'a' in the
>function during compilation itself? Is this a spec or a implementation spec?


This is very definitely how the language is specified to behave.
When you redefine 'a' you are introducing a new constant with the same
name, rather than changing the value of the old one. The old one goes
out of scope at that point, but function b was defined within the
scope of the first declaration and so uses its value of 1.


>WHat is the logic behind this? How can you access global variables within
>functions??


The logic is that variables (especially global ones!) are deemed to be
a bad thing and are outlawed in functional programs. That means that
the value returned by a function can depend only on the value of the
parameters you pass it and not when and where you call it from. The
upshot is that if you want to obtain the effect of global state, you
need to pass it as a parameter to any functions that use it. In this
case, if you wanted function b to use the 'current' version of 'a' then
you would have to pass it as an extra parameter to b.
      Ian
--
I.Glendinning@ecs.soton.ac.uk Ian Glendinning
Tel: +44 703 593081 Electronics and Computer Science
Fax: +44 703 593045 University of Southampton SO9 5NH England
[Similar responses arrived from acha@CS.CMU.EDU (Anurag Acharya),
preston@ariel.rice.edu (Preston Briggs), and ddean@rain.andrew.cmu.edu
(Drew Dean) -John]
--


Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.