-
Notifications
You must be signed in to change notification settings - Fork 104
Chaining
Roland edited this page Sep 15, 2018
·
2 revisions
Method chaining (also known as name parameter idiom), is a technique for invoking consecutively method calls in object-oriented style.
Each method returns an object, and method calls are chained together.
Moses offers chaining for your perusal.
Let's use chaining to get the count of evey single word in some lyrics (case won't matter here).
local lyrics = {
"I am a lumberjack and I am okay",
"I sleep all night and I work all day",
"He is a lumberjack and he is okay",
"He sleeps all night and he works all day"
}
-- split a text into words
local function words(line)
local t = {}
for w in line:gmatch('(%w+)') do t[#t+1] = w end
return t
end
local M = require 'moses'
local stats = M.chain(lyrics)
:map(words)
:flatten()
:countBy(string.lower)
:value()
-- => "{
-- => sleep = 1, night = 2, works = 1, am = 2, is = 2,
-- => he = 2, and = 4, I = 4, he = 2, day = 2, a = 2,
-- => work = 1, all = 4, okay = 2
-- => }"
For convenience, you can also use M(value)
to start chaining methods, instead of M.chain(value)
.
Note that one can use :value()
to unwrap a chained object.
local t = {1,2,3}
print(_(t):value() == t) -- => true