Python from Wise Guy's Viewpoint

Brian McNamara! gt5163b at prism.gatech.edu
Fri Oct 24 19:04:23 EDT 2003


Pascal Costanza <costanza at web.de> once said:
>Brian McNamara! wrote:
>> I can imagine Haskell code like
>> 
>>    y = do x <- myread "34"
>>           return x * 2
>>    z = do x <- myread "foo"
>>           return x * 2
>> 
>> where
>> 
>>    myread :: String -> Maybe a
>>    y, z :: Maybe Int
>> 
>> and "y" ends up with the value "Just 68" whereas "z" is "Nothing".
>
>The code you have given above doesn't give the user any feedback, right? 
>Do you really think that this is useful?

It is certainly useful if the strings are coming from a file read over
the network by a batch process that runs nightly on a machine sitting in
a closet.

But I suppose you really want this example

>>(defun f (x)
>>  (unless (< x 200)
>>    (cerror "Type another number"
>>            "You have typed a wrong number")
>>    (f (read)))
>>  (* x 2))

statically typed, huh?  Ok, I'll try.  If I come up short, I expect it's
because I'm fluent in neither Haskell nor Lisp, not because it can't be
done.

   readInt :: IO Maybe Int
   
   cerror :: String -> String -> IO Maybe a -> IO Maybe a
   cerror optmsg errmsg v = 
      do print errmsg
         print ("1: " ++ optmsg)
         print "2: Fail"
         mx <- readInt
         r <- if (maybe False (=1) mx) 
              then v
              else return Nothing
         return r

   f :: Int -> IO Maybe Int
   f x = do x' <- if x < 200
                  then cerror "Type another number"
                              "You have typed a wrong number"
                              (do mx <- readInt
                                  do x <- mx
                                     return f x)
                  else return (return (x * 2))
            return x'

I think that maybe works.  Perhaps someone who really knows Haskell and
has a Haskell compiler can check it and/or tidy it up a little if
necessary.

-- 
 Brian M. McNamara   lorgon at acm.org  :  I am a parsing fool!
   ** Reduce - Reuse - Recycle **    :  (Where's my medication? ;) )




More information about the Python-list mailing list