我写了一个处理程序
on test(action)
set x to "0"
set y to "1"
if action = "multiply"
return x*y
end if
return x+y
end test
我想将一些地方称为test()而没有任何参数,它返回sum,而在其他地方我想将参数作为“multiply”传递。
所以我正在寻找一种方法,如果我可以设置可选参数。
如果使用labelled parameters声明处理程序,则可以使用可选参数。但是,至少需要有两个参数才能使其有效。
例如:
on array from a as integer : 1 to b as integer
local a, b
set L to {}
repeat with i from a to b
set end of L to i
end repeat
L
end
此处理程序创建一个整数列表。它需要两个参数,a
和b
,其中a
是一个可选参数,分配了一个默认值1
。
从而,
array from 4 to 10
会产生这个清单:
{4, 5, 6, 7, 8, 9, 10}
然而:
array to 10
会产生一个列表,好像你用array from 1 to 10
调用了处理程序:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
您可以选择a
和b
,但是在调用处理程序时必须至少包含一个参数。
from
和to
是参数标签,其中有许多预定义的介词可用于标记参数。这些可以按任何顺序调用:
array from 10 to 1
是完全相同的
array from 1 to 10
并且不会反转列表顺序。
其他标签包括:
about, above, against, apart from, around, aside from, at,
below, beneath, beside, between, by, for, from, instead of,
into, on, onto, out of, over, since, thru, under
并且您可以定义与关键字given
一起使用的自己的标签,但是我将让您使用我离开的上面的链接阅读该标签。
test()
handler你的处理程序只接受一个参数,所以很遗憾它不是可选的。但是,如果你引入x
和y
作为参数,那么你可以使action
可选:
on test over {x, y} given function:action : "add"
local x, y, action
if action = "multiply" then return x * y
x + y
end test
然后:
test over {2, 5} given function:"multiply" --> 10
test over {2, 5} --> 7
这是一个侧面说明,与您的问题没有直接关系,但与您正在做的事情部分相关。
处理程序也可以作为参数传递,但不能作为可选项。我将把这个脚本留给你忽略和分析,并向你介绍这可以打开的可能性。如果您曾经使用过像Haskell或Lisp这样的函数式语言,那将非常熟悉:
to apply to {x as number, y as number} given function:func as handler
local x, y, func
script
property fn : func
end script
result's fn(x, y)
end apply
to add(x, y)
x + y
end add
to multiply(x, y)
x * y
end multiply
它没有像适当的函数式语言那样强大,但它比大多数AppleScripters实现AppleScript可以做的更强大:
apply to {5, 2} given function:multiply
但这超出了这个问题的范围,所以我会留下你的想象力来思考为什么这个结构可能比最初看起来更特殊。