今天我們再次換個語言,用 python 來解決非同步版的樹狀搜尋問題,並觀察三個語言之間的差異
import asyncio # 重要的 python 非同步工具
from typing import Union, List # 提供基本的型別輔助
class Node:
def __init__(self, id: str, text: str, children_ids: List[str]):
self._tag = "Node"
self.id = id
self.text = text
self.children_ids = children_ids
class NodeNotFoundError:
def __init__(self, id: str):
self._tag = "NodeNotFoundError"
self.id = id
async def get_node(id: str) -> Union[Node, NodeNotFoundError]:
nodes = {
"a": Node("a", "a", ["a1", "a2", "a33"]),
"a1": Node("a1", "a1", ["a11"]),
"a11": Node("a11", "a11", []),
"a2": Node("a2", "a2", []),
"a3": Node("a3", "a3", []),
}
target = nodes[id]
return target if target is not None else NodeNotFoundError()
async def get_name_by_id(target: str, id: str) -> str | None:
result = await get_node(id)
match result:
case Node():
if result.id == target:
return result.text
tasks = [get_name_by_id(target, child_id) for child_id in result.children_ids]
texts = await asyncio.gather(*tasks)
return next((text for text in texts if text is not None), None)
case NodeNotFoundError():
return None
async def main():
result = await get_name_by_id("a11","a1")
print(result)
if __name__ == "__main__":
asyncio.run(main())
Typescript | Kotlin | Python | 解決的問題 |
---|---|---|---|
async/await | suspend | async/await | 把非同步寫作風格簡化 |
Union Type (E|T) | Either<E|T> | Union Type (E|T) | 更加安全的進行錯誤處理 |
Promise.all | parMap | asyncio.gather | 更有效率的非同步流程控制 |
early return | when expression | match | 簡化程式碼複雜度 |
interface/type/class | class/object | class/dict | 資料與方法的封裝 |
觀察以上三種程式可以發現,各種現代化的程式語言環境中
早就已經準備好了函數式、結構化、物件導向這三種程式設計方法相互結合的空間
讓我們可以根據不同的場景,選擇合適的方式進行實作
題外話,前幾天我去了 JCConf,發現就連最保守的 Java 也預計將會加入 null-safety、structured concurrency 的支援! 我相信隨著 AI 與各種語言的成熟,比起「寫程式」本身,未來更重要的將會是能將前人的各種設計範式整合甚至優化的能力 ~