Jupyter 内核#
Jupyter Notebook 可以利用任何实现了 Jupyter 消息协议 的程序内核来执行代码。目前已有适用于 Python、Julia、Ruby、Haskell 以及 许多其他语言 的内核。
在本笔记本中,演示如何使用 Coconut 编程语言 执行代码。Coconut 是 Python 的变体,专为 简洁、优雅、Pythonic 的函数式编程 而构建。
在第一个示例中,将定义递归的 factorial
函数,这是一种根本上的函数式方法,不涉及任何状态变化或循环:
def factorial(n):
"""Compute n! where n is an integer >= 0."""
case n:
match 0:
return 1
match x is int if x > 0:
return x * factorial(x-1)
else:
raise TypeError("the argument to factorial must be an integer >= 0")
3 |> factorial |> print
CoconutSyntaxWarning: deprecated case keyword at top level in case ...: match ...: block (use Python 3.10 match ...: case ...: syntax instead) (line 3)
/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case n:
match 0:
return 1
match x is int if x > 0:
return x * factorial(x-1)
else:
raise TypeError("the argument to factorial must be an integer >= 0")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
CoconutSyntaxWarning: found deprecated isinstance-checking 'x is int' pattern; rewrite to use class patterns (try 'int(x)') or explicit isinstance-checking ('x `isinstance` int' should always work) (line 6)
/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
match x is int if x > 0:
return x * factorial(x-1)
else:
raise TypeError("the argument to factorial must be an integer >= 0")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
6
尽管这个示例非常简单,但模式匹配是 Coconut 最强大且最复杂的功能之一。
在第二个示例中,实现了快速排序算法。这个 quick_sort
算法使用了一系列新的语法结构:
def quick_sort(l):
"""Sort the input iterator using the quick sort algorithm."""
match [head] :: tail in l:
tail = reiterable(tail)
yield from quick_sort(left) :: [head] :: quick_sort(right) where:
left = (x for x in tail if x < head)
right = (x for x in tail if x >= head)
# By yielding nothing if the match falls through, we implicitly return an empty iterator.
[3,0,4,2,1] |> quick_sort |> list |> print
[0, 1, 2, 3, 4]
最后,看到异常是如何被引发的
x
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[3], line 1
----> 1 x #1: x
NameError: name 'x' is not defined