Skip to Content
深入理解運算原理|從簡單的機器到無所不能的程式
book

深入理解運算原理|從簡單的機器到無所不能的程式

by Tom Stuart
November 2017
Beginner to intermediate
344 pages
7h 2m
Chinese
GoTop Information, Inc.
Content preview from 深入理解運算原理|從簡單的機器到無所不能的程式
170
|
6
相等
如果想要找出 proc 裡的程式碼,唯一的方式就是呼叫它,所以如果以相同的引數呼叫
而會產生完全相同的結果,就算內部的程式碼並不相同,這兩個 proc 也可以互換。
這種根據外在可見的行為將兩件事物視為相等的想法,稱為
擴充相等
extensional
equality
)。
假設我們有個 proc
p
>> p = -> n { n * 2 }
=> #<Proc (lambda)>
我們可以讓另一個 proc
q
只接受一個引數,並僅以它來呼叫
p
>> q = -> x { p.call(x) }
=> #<Proc (lambda)>
p
q
很顯然是兩個不同的 proc,但它們是擴充相等,因為它們對任何引數都做了完全
相同的事情:
>> p.call(5)
=> 10
>> q.call(5)
=> 10
瞭解
p
等於
-> x {p.callx}
便開啟了重構的新機會。如果我們在自己的程式看到一
般的範式
-> x {p.callx}
,就可以選擇只以
p
替換整個運算式來剔除它,並且在某
些情況(稍後將會討論)可能也會決定進入另一個方向。
語法
Ruby 提供了建立和呼叫 proc 的語法選擇。從現在開始,我們將使用
-> arguments {body}
來建立 proc 和方括號來呼叫它:
>> -> x { x + 5 }[6]
=> 11
這樣很容易就能看到 proc 的主體和引數,而不會有太多礙手礙腳的額外語法。
問題
我們的目標是編寫知名的 FizzBuzz 程式:
無為的程式設計
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JSON實務手冊

JSON實務手冊

Tom Marrs

Publisher Resources

ISBN: 9789864766000