|
|
Darren New wrote:
> Invisible wrote:
>> The "get time" function just returns an I/O command object. You can
>> replace that function call with the command object it returns and the
>> meaning of the program is left completely unchanged. Thus it is
>> referentially transparent.
>
> So if I assign the result of "get time" to a variable and use that
> variable in multiple places, do I get the same time each place I use it,
> or different times? I think that's what's confusing me.
The key is "using".
Recall that the *only* way to *execute* an I/O action is to return it
from the "main" function. And, since you can only return a single
action, it's how you splice each mini-action into the giant-action
returned by "main" that counts. ;-)
If you splice in two copies of the self same action, that action gets
executed twice. It's that simple.
> S = get_time()
> print(S)
> do_long_task()
> print(S)
>
> I would think you *want* that to do something different from
> print(get_time())
> do_long_task()
> print(get_time())
>
> How would I write each of those in Haskell?
In Haskell, if you use the monadic "do" notation, then the syntax for
executing an action and putting its result into a variable is
do
...
x <- do_stuff
...
This is technically equivilent to
... do_stuff >>= \x -> ...
but less messy on paper. In your case, what you're trying to do is simply
do
t1 <- get_time
print t1
do_long_task
t2 <- get_time
print t2
as opposed to something like
do
s <- get_time
print s
do_long_task
print s
which just serves no useful purpose at all. Notice that it's the "<-"
that says "execute this *now*". In the second example, you only execute
the thing once, so it only happens once. It's really quite clear on paper.
In case you care, the desugared equivilents are:
get_time >>= \t1 -> (print t1 >> do_long_task >> get_time >>= \t2 ->
print t2))
and
get_time >>= \s -> (print s >> do_long_task >> print s)
You can see why people prefer the "do" notation...
--
http://blog.orphi.me.uk/
http://www.zazzle.com/MathematicalOrchid*
Post a reply to this message
|
|