type
status
date
slug
summary
tags
category
icon
password
Property
Jul 13, 2023 01:59 PM
Sequences & Data Abstraction

Sequences


List是任何值类型的一个序列
Sequence Abstraction

[a:b]可以从字符串中街区一个部分,索引从a开始,截取到索引b-1(包括b-1)
可以设置间隔进行跳过
可以进行加法

Sequence Processing

可以使用while循环进行遍历


for循环和while是等价的
读取超出索引范围值的时候会报错
Range

一样的是包前不包后,可以每隔多少个跳过
List Comprehensions

这种表达式并不会影响局部变量
Examples

Data Abstraction



Rational Numbers Arithmetic


利用selector取出分子和分母,然后做运算


Representing Rational Numbers

还需要有一些辅助函数
执行结果
Reducing to Lowest Terms

引入gcd 最大公约数
Abstraction Barriers

Violating Abstraction Barriers

这样是违反了抽象,因为没有传入rational构造函数。
因为你不敢保证你函数内部的实现就是一个Array,也许是其他的实现方式。只不过在这个地方是这样实现的。
一种别的实现方式
Dict Data
上面的函数也可以使用dict来实现,而不是数组
- 作者:Kitety
- 链接:https://www.kitety.com/article/cs-61a-8
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
相关文章