# 隐式编程

## 例子

### APL家族

avg=: +/ % #


+/通过将求和（+）插入（/）到一个阵列的所有元素之间来计算它们的合计值。#总计一个阵列的元素数目。%+/这个阵列的结果值除以#这个阵列的结果值。相同的隐式计算用APL的现代版本Dyalog APL[4]表达为：

avg ← +⌿ ÷ ≢


J语言中，欧拉公式${\displaystyle e^{ix}=\cos x+i\sin x}$可隐式表达为：

cos =: 2 o. ]
sin =: 1 o. ]
Euler =: ^@j. = cos j. sin


cos ← 2 ○ ⊢
sin ← 1 ○ ⊢
j   ← {⍺←0 ⋄ ⍺+0j1×⍵}  ⍝ j函数的定义不是隐式的
Euler ← *∘j = cos j sin


### Unix管道

sort | uniq -c | sort -rn


### Python

def sort(argv):
return sorted(argv, key=str)
def uniq_c(argv):
counts = {}
for i in argv:
counts[str(i)] = counts.get(str(i), 0) + 1
return [(v, int(k)) for k , v in counts.items()]
def sort_rn(argv):
sort_rk2 = sorted(argv, key=lambda x:str(x[1]), reverse=True)
return sorted(sort_rk2, key=lambda x:x[0], reverse=True)

a_list = [2, 5, 4, 14, 3, 1, 3, 12, 2]
a = sort(a_list)
b = uniq_c(a)
c = sort_rn(b)


from functools import partial, reduce

def compose(*func_list):
return partial(reduce, lambda argv,func:func(argv), func_list)

pipeline = compose(sort, uniq_c, sort_rn)
d = pipeline(a_list)
assert c == d


### 函数式编程

sum (x:xs) = x + sum xs
sum [] = 0


sum xs = foldr (+) 0 xs


sum = foldr (+) 0


p x y z = f (g x y) z


p = \x -> \y -> \z -> f (g x y) z
= \x -> \y -> f (g x y)
= \x -> \y -> (f . (g x)) y
= \x -> f . (g x)
= \x -> ((.) f) (g x)
= \x -> (((.) f) . g) x
= ((.) f) . g


p = ((.) f) . g


mf criteria operator list = filter criteria (map operator list)


mf = (. map) . (.) . filter


### 串接编程

: fib ( n -- m )
dup 2 < [
[ 1 - fib ] [ 2 - fib ] bi +
] unless ;


## 注释和引用

1. Tacit programming. [2022-06-11]. （原始内容存档于2022-07-20）.
2. Manuel Alcino Pereira da Cunha (2005) Point-free Program Calculation
3. ^ W. Neville Holmes, ed. (2006) Computers and People
4. ^ Dyalog APL. [2022-06-14]. （原始内容存档于2022-06-28）.
5. ^ 下列例子中的uniq_c()这么写是出于简短和完备，下面的替代写法更加有效率但需要符合unix的uniq应当处理sort之后的数据的原义。
def uniq_c(argv):
if argv == None or argv == []:
return
uniq = []
p, count = argv[0], 1
for c in argv[1:]:
if c == p:
count = count + 1
else:
uniq.append((count, p))
p, count = c, 1
uniq.append((count, p))
return uniq

6. ^ Name code not values. Concatenative.org. [2020-10-16]. （原始内容存档于2013-09-29）.
7. ^ pipermail. [2020-04-18]. （原始内容存档于2012-02-18）.