use*_*ser 20 ruby python syntax language-features
这种语言结构叫什么?
在Python中我可以说:
def a(b,c): return b+c
a(*[4,5])
Run Code Online (Sandbox Code Playgroud)
在Ruby中同样得到9.
def a(b,c) b+c end
a(*[4,5])
Run Code Online (Sandbox Code Playgroud)
当一个数组传递给一个需要多个参数的函数时,这叫做什么?
*运营商的名称是什么?
还有哪些语言支持这个很酷的功能?
six*_*ear 28
Python文档称之为Unpacking Argument列表.这是一个非常方便的功能.在Python中,您还可以使用双星号(**)将字典(哈希)解压缩为关键字参数.他们也反向工作.我可以定义一个这样的函数:
def sum(*args):
result = 0
for a in args:
result += a
return result
sum(1,2)
sum(9,5,7,8)
sum(1.7,2.3,8.9,3.4)
Run Code Online (Sandbox Code Playgroud)
将所有参数打包到任意大小的列表中.
Mat*_*kel 10
在红宝石中,它通常被称为"啪啪".
同样在ruby中,您可以使用它来表示"列表中的所有其他元素".
a, *rest = [1,2,3,4,5,6]
a # => 1
rest # => [2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
它也可以出现在赋值运算符的任一侧:
a = d, *e
Run Code Online (Sandbox Code Playgroud)
在这种用法中,它有点像scheme的cdr,虽然它不一定只是列表的头部.
典型的术语称为"将函数应用于列表",或简称为"应用".
见http://en.wikipedia.org/wiki/Apply
自从1960年奇迹开始以来它一直存在于LISP中.高兴的python重新发现它: - }
Apply通常位于列表或列表(如数组)的表示上.但是,可以将函数应用于来自其他方法的参数,例如结构.我们的PARLANSE语言有固定的类型(int,float,string,...)和结构.奇怪的是,函数参数列表看起来很像结构定义,而在PARLANSE中,它是一个结构定义,您可以将PARLANSE函数"应用"到兼容的结构中.您也可以"制作"结构实例,因此:
(define S
(structure [t integer]
[f float]
[b (array boolean 1 3)]
)structure
)define s
(= A (array boolean 1 3 ~f ~F ~f))
(= s (make S -3 19.2 (make (array boolean 1 3) ~f ~t ~f))
(define foo (function string S) ...)
(foo +17 3e-2 A) ; standard function call
(foo s) ; here's the "apply"
PARLANSE看起来像lisp但不是.
| 归档时间: |
|
| 查看次数: |
5889 次 |
| 最近记录: |