Python from Wise Guy's Viewpoint

Dirk Thierbach dthierbach at gmx.de
Fri Oct 24 19:37:38 EDT 2003


Pascal Costanza <costanza at web.de> wrote:
> Brian McNamara! wrote:

>>> Have you ever used a program that has required you to enter a
>>> number?  The check whether you have really typed a number is a
>>> dynamic check, right?

This dynamic check doesn't necessarily translate to a type check.
Not everything boils down to types just because you're using "numbers".
As Brian has shown, you can use a type that says "maybe it is a
number, maybe it isn't". And that is statically safe, even if we
cannot decide at compile-time if it will be a number of not.

>> Yes, but this doesn't imply we can't write a statically-typed program to
>> handle the situation...

> The code you have given above doesn't give the user any feedback, right? 
> Do you really think that this is useful?

There's no problem with adding feedback, other than you have now to
package up the whole thing into the IO monad, because you have side
effects. The important point is the "Maybe" type. With a function like

multiread :: IO (Maybe Int)

you can write code as in

f = do z <- multiread
       let y = do x <- z 
                  return (x * 2) 
       return y

The outer "do" handles the IO monad, the inner "do" will ignore the
calculation if there is no value available. Here's a (very quickly
written, and very bad; I am sure it can be done with more elegance)
implementation of multiread:

myread :: String -> IO (Maybe Int) -> IO (Maybe Int)
myread "" _       = return Nothing
myread s failcont = result (reads s) where
  result [(x, "")] = return (Just x)
  result _         = failcont

multiread :: IO (Maybe Int)
multiread = do
  s <- getLine
  myread s (print "Reenter number, or press Enter to abort" >> multiread)


- Dirk





More information about the Python-list mailing list