# solution provided by GitHub user clean99

def count_pairs(x):
    counted_pairs = None
    def is_counted_pair(current_counted_pairs, x):
        return (False
                if is_none(current_counted_pairs)
                else True
                if head(current_counted_pairs) is x
                else is_counted_pair(tail(current_counted_pairs), x))
    def count(x):
        nonlocal counted_pairs
        if not is_pair(x) or is_counted_pair(counted_pairs, x):
            return 0
        else:
            counted_pairs = pair(x, counted_pairs)
            return (count(head(x)) +
                    count(tail(x)) +
                    1)
    return count(x)

three_list = llist("a", "b", "c")
one = pair("d", "e")
two = pair(one, one)
four_list = pair(two, "f")
seven_list = pair(two, two)
cycle = llist("g", "h", "i")
set_tail(tail(tail(cycle)), cycle)

# return 3; return 3; return 3
print(count_pairs(three_list))
print(count_pairs(four_list))
print(count_pairs(seven_list))

# return 3
print(count_pairs(cycle))
