Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.forth > #22505
| From | "WJ" <w_a_x_man@yahoo.com> |
|---|---|
| Newsgroups | comp.lang.forth |
| Subject | Re: DSPic FORTH |
| Date | 2013-05-11 11:32 +0000 |
| Organization | A noiseless patient Spider |
| Message-ID | <kmla86$d4a$1@dont-email.me> (permalink) |
| References | (5 earlier) <9c71dd7e-8976-42ae-b379-4f9c88330425@lb9g2000pbb.googlegroups.com> <kcvccb$rdc$2@dont-email.me> <ffac2d17-5cae-4aa8-bc19-d14cf1e5604d@v9g2000pbi.googlegroups.com> <kd1vot$ba$1@dont-email.me> <4128b941-bb95-4ee5-a56b-45484a6f0abb@i2g2000pbi.googlegroups.com> |
Hugh Aguilar wrote:
> On Jan 14, 3:09 pm, rickman <gnu...@gmail.com> wrote:
> > Care to clue me in as to why closures are so important?
>
> No, I wouldn't care to --- read any novice-level book on programming
> any modern language for this information.
A couple of simple closure examples in Lua.
-- A function that returns a closure.
function make_stepper()
local i = 0
return function () i = i + 1 return i end
end
function make_matrix (height, width, func)
mat = {}
for row = 1, height do
mat[row] = {}
for col = 1, width do
mat[row][col] = func(row,col)
end
end
return mat
end
function print_matrix (mat)
for _, row in ipairs(mat) do
for _, x in ipairs(row) do io.write(string.format("%3d",x)) end
print()
end
end
print_matrix( make_matrix( 5, 5, function(y,x) return y*x end ))
===>
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
print_matrix( make_matrix( 4, 5, make_stepper() ))
===>
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
-- A function that returns a closure.
function make_counter ()
local cnt = 0
return
function (arg)
if arg then
return cnt
else
cnt = cnt + 1
end
end
end
counts = {string=make_counter(), number=make_counter(), table=make_counter()}
for _, x in ipairs({1,2,3,4,5,"a","b",'c',{},{}}) do
counts[ type(x) ]()
end
for key, val in pairs( counts ) do
print( val('report') .. " " .. key .. 's' )
end
===>
5 numbers
3 strings
2 tables
Back to comp.lang.forth | Previous | Next | Find similar
Re: DSPic FORTH "WJ" <w_a_x_man@yahoo.com> - 2013-05-11 11:32 +0000
csiph-web