What have you found for these years?

2007-09-02

Superators Add New Operators to Ruby

來自 ptt ruby 板:

 作者  godfat (godfat 真常)                                        看板  Ruby 
標題 Re: [連結] Superators Add New Operators to Ruby
時間 Sun Sep 2 11:49:58 2007
───────────────────────────────────────

※ 引述《yjc1 (..........)》之銘言:
: http://jicksta.com/articles/2007/08/29/superators-add-new-operators-to-ruby
: 非常有趣的東西.

老實講看到這個我真的覺得很不可思議,因為那乍看之下根本不合 ruby 語法。
網頁上也有一段 updated 說:

Update: There seems to be some confusion that Superators are a C extension
that modify Ruby’s internals. A valid Superator is actually just valid
Ruby—something we’ve had at our disposal this whole time!

看來不只是我覺得這很不可思議啊 XD
但是事實上證明只是我沒搞清楚 ruby 的 operator binding 而已。
本來我是想直接翻 source code, 不過他寫得滿漂亮的,半夜翻看了一下,
覺得短時間內恐怕不容易看懂,儘管只有百來行而已。

先翻翻網頁,看到這句話就了然了:

foo ++- bar
is equivalent to
foo.+(bar.-@().+@())

所以他必然是在 bar 底下開一個空間去存 operator,
對於 foo 的 binary operator 呼叫到時,再去檢查是否 match pattern.
這個實做起來應該還算滿複雜的,他一百行就寫完確實滿厲害的。

然而更重要的是,這也代表著 superator 有許許多多的缺點,
使得我覺得實際上這東西也只是好玩而無太多實用上的意義。
如作者也說了,對於 true, false, nil, Symbols or Fixnums, 這些
是無效的,因為他們本身就有那些 unary operator.

另一點則是他能支援的 pattern 被固定在只能有:

(binary operator)(unary operator)+

而 unary operator 在 ruby 裡只有三種:+ - ~
意味著你的 pattern 一定得是一堆 +, -, 或是 ~...

於是這也許可以拿來做摩斯電碼之類的﹍﹍

msg <<++--+-++--++--+++-+
msg <<--++--++-----+--+--

於是 + 表示長音,- 表示短音之類的﹍﹍
不過這樣為何不乾脆寫成這樣:

msg << '++--+-++-....'

好像還是沒什麼意義啊。
所以原本很同意這句:Dear demagogues of domain specificity!
我恐怕要收回來了 XD

不過最慘的應該還是,由於 operator 事實上還是分開的,
所以一定會有這種狀況發生:

class Array
superator "<---" do |op|
self << op
end
end

s = 'XD'
-s
-s
-s
[] < s # => ['XD']

是真的很好玩沒錯啦,可以定義 ++ 去模仿 haskell,
只是實用性﹍﹍所以作者也強調:

I should note that I strongly frown upon any use of Superators outside
of the DSL space. Don’t use it in your company’s Rails app controllers.
Use it in your tenderly crafted Ruby DSLs where they make sense.

不過我在想,是否可以利用相似的概念,玩點別的東西?

--

--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.135.28.18

0 retries:

Post a Comment

Note: Only a member of this blog may post a comment.



All texts are licensed under CC Attribution 3.0