[plt-scheme] HtDP in Python!

From: Arthur Nunes-Harwit (anh at cs.rit.edu)
Date: Mon Feb 16 13:31:19 EST 2009

Hi,

   I'm interested in getting reactions to doing programming HtDP style but 
in Python.  Here is an example.

   Thanks.

-Arthur

# Data Definitions:
# a linkedList is either
# + an emptyList
# + an elementList with parts 
#   * o, where o is an object and 
#   * ll, where ll is a linkedList

class emptyList(tuple):
     pass

# Constructor: nullList: () -> linkedList
def nullList():
     return emptyList(())

class elementList (tuple):
     def head(self):
         return self[0]
     def tail(self):
         return self[1]

# Constructor: cons: object linkedList -> linkedList
def cons(o, ll):
     return elementList((o, ll));

# Contract: length: linkedList -> nat

# Purpose: to count the number of objects in a linkedList

# Example: length(cons('a', cons('b', nullList()))) == 2

# Template:
# def length(ll):
#    if isinstance(ll, emptyList):
#        return ...
#    elif isinstance(ll, elementList):
#        return ... ll.head() ... length(ll.tail()) ...
#    else:
#        raise RuntimeError("length's input not a linkedList")

# Definition:
def length(ll):
     if isinstance(ll, emptyList):
         return 0
     elif isinstance(ll, elementList):
         return 1 + length(ll.tail())
     else:
         raise RuntimeError("length's input not a linkedList")

# Tests:
length(nullList()) == 0
length(cons('a', cons('b', nullList()))) == 2





Posted on the users mailing list.