Protocol is a set of Interfaces and formally defined set of Rules, usually defined by FSM.

In ML one can use a protocol name just like any other named type — for example, to create a collection of objects that have different types but that all conform to a single protocol (implemented a set of interfaces). When you work with values whose type is a protocol type, methods outside the protocol definition are not available.

Type-class is a generalization of the concept of conforming to a protocol.

Closures which follow (implement) the same protocol are composable and their composition could be statically type-checked.

Python's Iterator protocol

An Iterator is simply a function which returns an object on which you can call __next__() method, which returns a next value. When there is nothing more to return it raises a StopIteration exception. Together the method, the exception and the rule to how to catch the exception constitutes the Iterator Protocol.

it = iter([1,2,3])

Python's Generators

Using yield instead of return in a function makes it a Generator (an object of different a type from Iterator).

def range(n):
    num = 0
    while num < n:
        yield num
        num += 1

Generator comprehension and composition

ss = (i*i for i in range(1000000))
def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

Rust's iterators

Here is what it takes to be an Iterator defined informally as a protocol

trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;

next will return Some(Item) as long as there are elements, and once they've all been exhausted, will return None to indicate that iteration is finished.

Last modified 15 months ago Last modified on Nov 18, 2018, 5:15:14 AM
Note: See TracWiki for help on using the wiki.