Loading AI tools
越位規則(Off-side rule)是指程式語言中,用縮排來表示塊結構的範圍。這名詞是來自Peter J. Landin,是足球中越位(offside)的雙關語。
越位規則,定義於Peter J. Landin在1966年叫做《The Next 700 Programming Languages》的文章中[1]:
“ | 縮排被用來指示程式結構。物理的ISWIM可以依據一個未指明的參數即短語範疇的一個子集來定義,它的實例受到遵從叫做「越位規則」的規則的佈局的限制。包含一個短語的第一個符號作為原點的右下象限必定包含整個短語,除了可能的被括號包圍的子段落之外。這個規則有三個重要特徵:它基於了對齊,而非字元寬度,因而它同等的適合於手寫、排字和打字的文字。它的使用不是強制的,它可以自由的同更常規的替代者比如標點符號一起混合使用。還有它是以一種系統性方式結合進入ISWIM中的,這容許了替代者而不改變ISWIM的其他特徵,它可以應用於其他語言。 | ” |
這個規則被解讀為是一種詞法約定:任何非空白記號,當出現在上一行這種記號左側之時,被接受為一個新宣佈的開始[2]。
以Haskell語言的黃金規則為範例:作為某個表達式一部份的代碼應該比這個表達式的開始處要縮排進去,即使這個表達式不是此行的最左元素。所有組合起來的表達式必須精確的對齊,在表達式的左側的所有東西都被當作縮排,即使不是空白。當一個表達式的開始處不是一行的開始的時候,表達式的後續部分可以只比包含這個表達式開始的那一行要縮排進去。由花括號{...}
和分號;
組織起來的代碼塊可不採用越位規則。下面以將適用越位規則的do
控制結構嵌入if...then...else
為例:
if foo
then do first thing
second thing
third thing
else do something_else
|
if foo
then do
first thing
second thing
third thing
else do
something_else
|
if foo
then do
first thing
second thing
third thing
else do
something_else
|
垂直對齊[注 1] | 懸掛縮排[注 2] | 懸掛縮排[注 3] |
以下是一個Python語言程式的例子,其中用縮排表示其程式區塊[3]:
def is_even(a: int) -> bool:
"""确定数a是否是偶数."""
if a % 2 == 0:
print('偶数!')
return True
print('奇数!')
return False
Python中括號內多行代碼會隱式的接合在一起,也有着相應的縮排規則:
# 参数比后续部份多一层缩进
def long_function_name(
var_one, var_two, var_three,
var_four):
# 可选的圆括号内后续行多一层缩进,注意这里关键字在行首
if (this_is_first_thing
and that_is_second_thing):
do_something()
# 可选的圆括号内后续行不额外缩进,同类语言元素垂直对齐
elif (this_is_third_thing and
that_is_fourth_thing):
do_something_different()
# 悬挂缩进,参数比行首缩进一层
spam = long_function_name(
arg_one, arg_two,
arg_three, arg_four)
# 按开定界符垂直对齐
eggs = long_function_name(arg_one, arg_two,
arg_three, arg_four)
#可选的闭括号位置
my_list = [
1, 2, 3,
4, 5, 6,
]
# 可选的闭括号位置
my_set = {
1, 2, 3,
4, 5, 6,
}
#light "off"
)where
、let
、do
或of
子句在花括號省略的時候)Indentation, used to indicate program structure. A physical ISWIM can be defined in terms of an unspecified parameter: a subset of phrase categories, instances of which are restricted in layout by the following rule called "the offside rule." The southeast quadrant that just contains the phrase's first symbol must contain the entire phrase, except possibly for bracketed subsegments. This rule has three important features. It is based on vertical alignment, not character width, and hence is equally appropriate in handwritten, typeset or typed texts. Its use is not obligatory, and use of it can be mixed freely with more conventional alternatives like punctuation. Also, it is incorporated in ISWIM in a systematic way that admits of alternatives without changing other features of ISWIM and that can be applied to other languages.
Seamless Wikipedia browsing. On steroids.
Every time you click a link to Wikipedia, Wiktionary or Wikiquote in your browser's search results, it will show the modern Wikiwand interface.
Wikiwand extension is a five stars, simple, with minimum permission required to keep your browsing private, safe and transparent.