# 函式實字

March 4, 2022

``````function sort(lt) =
let(leng = len(lt))
leng <= 1 ? lt :
let(
pivot = lt[0],
before = [for(j = 1; j < leng; j = j + 1) if(lt[j] < pivot) lt[j]],
after =  [for(j = 1; j < leng; j = j + 1) if(lt[j] >= pivot) lt[j]]
)
[each sort(before), pivot, each sort(after)];

// ECHO: [1, 2, 3, 5, 6, 7, 8, 10]
echo(sort([3, 1, 2, 5, 7, 6, 10, 8]));
``````

## 建立函式值

``````function sort(lt, compare) =
let(leng = len(lt))
leng <= 1 ? lt :
let(
pivot = lt[0],
before = [for(j = 1; j < leng; j = j + 1) if(compare(lt[j], pivot) < 0) lt[j]],
after =  [for(j = 1; j < leng; j = j + 1) if(compare(lt[j], pivot) >= 0) lt[j]]
)
[each sort(before, compare), pivot, each sort(after, compare)];
``````

``````compare = function(a, b) a - b;
``````

``````compare_functions = [
function(a, b) a - b,
function(a, b) b - a
];
``````

``````// ECHO: [10, 8, 7, 6, 5, 3, 2, 1]
echo(
sort(
[3, 1, 2, 5, 7, 6, 10, 8],
compare = function(a, b) b - a
)
);
``````

``````echo(
sort(
["a", "aa", "a", "aaa"],
compare = function(a, b) len(a) - len(b)
)
);
``````

## function vs function？

OpenSCAD 的函式實字，是在 2021.01 版本加入的特性，很可惜地，它使用了與函式定義相同的關鍵字 `function`，例如，以下是個 `ascending` 函式定義：

``````function ascending(a, b) = a - b;
``````

``````descending = function(a, b) b - a;
``````

OpenSCAD 的函式實字，其實就相當於其他語言中的 lambda 運算式（lambda expression）匿名函式（anonymous function）一級函式（first class function）之類的特性，如果能採用 `(a, b) -> a - b` 或者 `lambda(a, b) a - b` 之類語法，就不會與函式定義混淆，無論如何，既然函式實字也是使用 `function` 關鍵字，習慣就好…XD

``````leng = function(lt) len(lt);
``````

``````factorial = function(n) n == 1 ? 1 : n * factorial(n - 1);

// ECHO: 120
echo(factorial(5));
``````

``````function sort(lt, compare = function(a, b) a - b) =
let(leng = len(lt))
leng <= 1 ? lt :
let(
pivot = lt[0],
before = [for(j = 1; j < leng; j = j + 1) if(compare(lt[j], pivot) < 0) lt[j]],
after =  [for(j = 1; j < leng; j = j + 1) if(compare(lt[j], pivot) >= 0) lt[j]]
)
[each sort(before, compare), pivot, each sort(after, compare)];

// ECHO: [1, 2, 3, 5, 6, 7, 8, 10]
echo(sort([3, 1, 2, 5, 7, 6, 10, 8]));
``````