未登录,请登录后再发表信息
最新评论 (0)
播放视频

【用代数讲计算机科学】协约

CS in Algebra: Contracts

你已经见过几个使用两个数字作为参数并返回一个数字的函数
You’ve already seen several functions that take in 2 numbers and return a number
像 加 减 乘 除
such as addition, subtraction, multiplication and division.
star triangle 和 circle函数
The functions star, triangle and circle
都是使用一个数字和两个字符串作为参数并返回一个图片
all take in a number and two strings, returning an image.
这就是协议的来由
That’s where the contract comes in.
协议就是一个用人类语言记录所有函数的工具
A contract is a tool to help us document all of the functions in our language.
它就像一个指定函数的指导手册
It’s like an instruction manual for a specific function.
让我们用triangle函数举个例子
Let’s use the triangle function as an example.
每个协议都由三个部分组成
Each contract is made up of three parts
名字 域和范围
the name the domain and the range
函数的名字应该是不言自明的
The name should be pretty self-explanatory
因此triangle函数的名字就是triangle
and in this case, the name of our function is triangle.
一个函数的域就是函数所期望的
The domain of a function is a list of the types of data
参数数据类型列表
the function expects in the order it expects them.
理解域不是参数的名称是很重要的
It’s important to understand that the domain is NOT the names of the inputs
它不是大小 风格 或颜色
like size style or color
而是函数所期待的数据类型 像数字或者字符
but the data types they expect like number and string.
我们协议的最后一个元素就是范围
The final element of our contract is the range
它表示一个函数的返回值类型
which tells us the data type that a function returns
triangle函数有一个图片范围
The triangle function has a range of image
我们使用数据类型而不是值
We use types instead of values
因为当我们写协议的时候我们想要它更通用
when we write a contract because we want to be more general.
星星可以是任何大小的
A star could be any size
所以star函数的域的
so the domain for the star specifies
第一个参数可以是任何数值
that the first input could be any number value
如果我们把语言看做乐高积木集合
If we think of a language as a collection of Lego pieces
那么协议就像玩具里的凸凹槽
the contracts are the tabs and slots
它告诉我们每一部分应该怎样连接
that tell us how each piece can connect.
当你遇到并最终写出更多的函数
As you encounter and eventually write more functions
你会想要在记录中记下它们的协议
you’ll want to document their contracts in the contract log
那么记录就是你的语言手册
The log will serve as your manual for the language
它会在你写更复杂的程序时给你真正的帮助
which will be really helpful when you start to write more complex programs.
下一期 你会有机会写几个不同的函数
In the next stage, you’ll get a chance to write a number of different functions
并且为它们写上协议
and then write a contract for each one.
为了之后的引用 确保你在记录中为这些函数添加了协议
Make sure you also add these contracts to your log for reference later on

发表评论

译制信息
视频概述

本篇视频讲述了如何设计函数协议以及协议在以后的使用中将起到什么作用

听录译者

收集自网络

翻译译者

【B】Cod

审核员

自动通过审核

视频来源

https://www.youtube.com/watch?v=X8L259cdfns

相关推荐