CS 61A

Time: Wed 9/20/17 3:30 pm

Run Down of Conceptual Topics So Far

Weekly Misc: Data Abstraction

One data abstraction introduced to the lecture so far: Rational numbers, represented by their numerators and denominators. Define constructors and selectors in very generalized terms.

Discuss the differences among Python list (& list comprehensions, unpacking), str (& some literals), dict. Furthermore, their use cases and how they can be useful to abstract data (like how list can be used to represent a rational number behind an abstraction barrier).

Oh, and what's an abstraction barrier after all?

If with extra time, try to implement data abstraction with higher order functions only.

Possible Implementations

# Functional version: Higher order functions

def make_ticket(ticket_type, ticket_price):
    """ Makes a ticket. """

    def ask(something):
        """ It tells you something (the something) you are asking for. """

        if something == "type":
            return ticket_type
        if something == "price":
            return ticket_price
        return "Uh oh"

    return ask

def ask_ticket_type(ticket):
    return ticket("type")

def ask_ticket_price(ticket):
    return ticket("price")
# Lab version: Representing a ticket with a list

def make_ticket(ticket_type, ticket_price):
    return [ticket_type, ticket_price]

def ask_ticket_type(ticket):
    return ticket[0]

def ask_ticket_price(ticket):
    return ticket[1]
# Super version: A number is issued to represent a ticket

tickets = []

def make_ticket(ticket_type, ticket_price):
    ticket = [ticket_type, ticket_price]
    tickets.append(ticket)
    return len(tickets) - 1

def ask_ticket_type(ticket):
    return tickets[ticket][0]

def ask_ticket_price(ticket):
    return tickets[ticket][1]
# Hyper version: Closure

def ticketmaster():

    tickets = []

    def make_ticket(ticket_type, ticket_price):
        ticket = [ticket_type, ticket_price]
        tickets.append(ticket)
        return len(tickets) - 1

    def ask_ticket_type(ticket):
        return tickets[ticket][0]

    def ask_ticket_price(ticket):
        return tickets[ticket][1]

    def print_tickets():
        print(tickets)

    return [make_ticket, ask_ticket_type, ask_ticket_price, print_tickets]

[make_ticket, ask_ticket_type, ask_ticket_price, print_tickets] = ticketmaster()