菱形语言
Rhombus Language

原始链接: https://rhombus-lang.org

这段代码定义了几个类和函数,展示了面向对象和函数式编程的概念。 `Rect` 类表示一个矩形,具有 `left`,`top`,`right` 和 `bottom` 坐标。`area` 函数计算 `Rect` 的面积。`rect_like_to_rect` 函数将不同的类似矩形的数据结构(`Rect` 对象,带有 "LT" 和 "RB" 键的字典,或带有 "TL" 和 "RB" 键的字典)转换为标准的 `Rect` 对象。 `all_same` 函数检查字符串列表中的所有元素是否相同。 `Posn` 类表示一个具有 x 和 y 坐标的点。`flip_all` 函数接受一个 `Posn` 对象列表,并返回一个新的列表,其中 x 和 y 坐标已交换。 `Tree` 类表示一个树形结构,具有 `val` 和 `children` 列表(其他 `Tree` 对象)。`flatten` 方法递归地将树展平为一个值列表。 `OriginRect` 宏用于创建一个原点位于 (0, 0) 且具有指定右下坐标的 `Rect`。`area` 函数被重新定义以同时处理标准 `Rect` 对象和 `OriginRect` 对象,并相应地计算面积。

Hacker News 最新 | 过去 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 Rhombus 语言 (rhombus-lang.org) 8 分 swatson741 1 小时前 | 隐藏 | 过去 | 收藏 | 讨论 加入我们,参加 6 月 16-17 日在旧金山举行的 AI 初创公司学校! 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系我们 搜索:

原文
 
class Rect(left, top, right, bottom)
                     
fun area(r):
  let w = r.right - r.left
  let h = r.bottom - r.top
  w*h
                                
area(Rect(0, 0, 10, 5))

 
class Rect(left, top, right, bottom)
                     
fun rect_like_to_rect(v):
  match v
  | Rect(_, _, _, _): v
  | {"LT": [l, t], "RB": [r, b]}: Rect(l, t, r, b)
  | {"TL": [t, l], "RB": [b, r]}: Rect(l, t, r, b)
                                
rect_like_to_rect({"TL": [0, 2], "RB": [10, 5]})

rect_like_to_rect({"LT": [0, 2], "RB": [10, 5]})

                     
fun all_same([str0, str, ...]):
  all(str0 == str, ...)
 
all_same(["hello", "hello", "hello"])

all_same(["hello", "goodbye", "hello"])

 
class Posn(x, y)
 
fun flip_all([Posn(x, y), ...]):
  [Posn(y, x), ...]
 
flip_all([Posn(1, 2), Posn(3, 4)])

flip_all([Posn(5, 6)])

 
class Tree(val, children :: List.of(Tree)):
  method flatten(): 
    for fold(lst = [val]) (child in children):
      
      lst ++ child.flatten()
 
Tree(1, [Tree(2, [Tree(4, [])]),
         Tree(3, [Tree(5, [])])])
  .flatten() 
 
class Rect(left, top, right, bottom)
 
bind.macro 'OriginRect($right, $bottom)':
  'Rect(0, 0, $right, $bottom)'
 
fun area(r):
  match r
  | OriginRect(r, b): r*b
  | Rect(l, t, r, b): (r-l)*(b-t)
                      
area(Rect(0, 0, 10, 5))

联系我们 contact @ memedata.com