Skip to main content

用流替换迭代器并享受不可变。

项目描述

荣誉SICP 3.5 流。它显示了一种以不同方式查看“变化”数据的方法。

介绍

迭代器实际上无法恢复地消耗其中的数据。这对于(不是纯的,而是类似 Lisp 的)函数式编程是不可接受的。这个包是为解决这个问题而构建的。

Stream 被设计为不可变的,但不是由代码强制执行的。s._head防止用or做任何事情s._tail

用法(所有代码都完整)

## Importing and Constructing a Stream
from sicp_streams import Stream

s = Stream("axolotl", "barnacle", "coral")

# Equivalently, use another stream as last element means "rest"
# s = Stream("axolotl", Stream("barnacle", Stream("coral", None)))

# Equivalently, use a callable as last element also means "rest", and will not be called until it is necessary
# s = Stream("axolotl", lambda: Stream("barnacle", lambda: Stream("coral", lambda: None)))

# Therefore, it is possible to construct a stream that never ends
ones = Stream(1, lambda: ones)

## Get Data from It
assert s.head == "axolotl"
assert s.tail.head == "barnacle"
assert s.tail.tail.head == "coral"
assert s.tail.tail.tail is None  # end of stream is None

## Get Data by subscripting
assert (s[0], s[1], s[2]) == ("axolotl", "barnacle", "coral")

## Turn into an Iterator
it = iter(s)
assert next(it) == "axolotl"
assert next(it) == "barnacle"
assert next(it) == "coral"

## Construct from an iterable
Stream.from_iterable([1, 2, 3])


## Construct from generator function
@Stream.from_generator_function
def counts(n):
    while True:
        yield n
        n += 1


integers = counts(1)

工具箱类比itertools和迭代器相关的内置函数

from sicp_streams import Stream
import streamtools

# some of them have different name (for obvious but unnecessary reason)
# map -> smap
streamtools.smap(lambda x: x + 1, Stream(1, 2, 3))
# filter -> sfilter
streamtools.sfilter(lambda x: x % 2 == 0, Stream(1, 2, 3))
# zip -> szip
streamtools.szip(Stream(1, 2, 3), Stream(4, 5, 6))
# islice -> sslice
streamtools.sslice(Stream(1, 2, 3, 4, 5), 2, 4)

演示,重新实现 SICP 3.5(不是全部)

import streamdemo

项目详情


下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

源分布

sicp-streams-0.2.0.tar.gz (7.5 kB 查看哈希

已上传 source

内置分布

sicp_streams-0.2.0-py3-none-any.whl (7.9 kB 查看哈希

已上传 py3