Skip to content

Commit

Permalink
doc fixes, plus embarrassing func.curry has been renamed bind1 (curry…
Browse files Browse the repository at this point in the history
… still as alias)
  • Loading branch information
stevedonovan committed Sep 18, 2013
1 parent a62d30d commit d5f739d
Show file tree
Hide file tree
Showing 11 changed files with 61 additions and 68 deletions.
2 changes: 1 addition & 1 deletion doc/config.ld
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
project = 'Penlight'
description = 'Penlight Lua Libraries 1.2.1'
description = 'Penlight Lua Libraries 1.3.1'
full_description = 'The documentation is available @{01-introduction.md|here}.'
title = 'Penlight Documentation'
dir = 'api'
Expand Down
60 changes: 21 additions & 39 deletions doc/manual/01-introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,6 @@ useful message. This is more appropriate behaviour for a _script_ than providing
a stack trace. (However, this default can be changed.) The lexer functions always
throw errors, to simplify coding, and so should be wrapped in `pcall`.

By default, the error stacktrace starts with your code, since you are not usually
interested in the internal details of the library. ??

If you are used to Python conventions, please note that all indices consistently
start at 1.

Expand All @@ -50,14 +47,6 @@ either [alien](http://alien.luaforge.net/) or be using
[LuaJIT](http://luajit.org) as well. (The fallback is to call the equivalent
shell commands.)

Some of the examples in this guide were created using
[ilua](http://lua-users.org/wiki/InteractiveLua), which doesn't require '=' to
print out expressions, and will attempt to print out table results as nicely as
possible. This is also available under Lua for Windows, as a library, so the
command `lua -lilua -s` will work (the s option switches off 'strict' variable
checking, which is annoying and conflicts with the use of `_DEBUG` in some of
these libraries.

### To Inject or not to Inject?

It was realized a long time ago that large programs needed a way to keep names
Expand Down Expand Up @@ -111,16 +100,12 @@ make Penlight available within a module:

return M

The default is to put Penlight into `_ENV`, which has the unintended effect of
The default is to put Penlight into `\_ENV`, which has the unintended effect of
making it available from the module (much as `module(...,package.seeall)` does).
To satisfy both convenience and safety, you may pass `true` to this function, and
then the _module_ `M` is not the same as `_ENV`, but only contains the exported
then the _module_ `M` is not the same as `\_ENV`, but only contains the exported
functions.

With Penlight after 0.9, please note that `require 'pl.utils'` no longer implies
that a global table `pl.utils` exists, since these new modules are no longer
created with `module()`.

Otherwise, Penlight will _not_ bring in functions into the global table, or
clobber standard tables like 'io'. require('pl') will bring tables like
'utils','tablex',etc into the global table _if they are used_. This
Expand Down Expand Up @@ -206,7 +191,7 @@ than merely returning a `nil` that will cause problems later.
Many functions in Penlight themselves take function arguments, like `map` which
applies a function to a list, element by element. You can use existing
functions, like `math.max`, anonymous functions (like `function(x,y) return x > y
end`), or operations by name (e.g '*' or '..'). The module `pl.operator` exports
end` ), or operations by name (e.g '*' or '..'). The module `pl.operator` exports
all the standard Lua operations, like the Python module of the same name.
Penlight allows these to be referred to by name, so `operator.gt` can be more
concisely expressed as '>'.
Expand All @@ -217,7 +202,7 @@ have `ls:filter('>',0)`, which is a shortcut for

Finally, `pl.func` supports _placeholder expressions_ in the Boost lambda style,
so that an anonymous function to multiply the two arguments can be expressed as
`_1*_2`.
`\_1*\_2`.

To use them directly, note that _all_ function arguments in Penlight go through
`utils.function_arg`. `pl.func` registers itself with this function, so that you
Expand All @@ -228,10 +213,9 @@ can directly use placeholder expressions with standard methods:
{11,21,31}

Another option for short anonymous functions is provided by
`utils.string_lambda`; since 0.9 you have to explicitly ask for this feature:
`utils.string_lambda`; this is invoked automatically:

> L = require 'pl.utils'.string_lambda
> = List{10,20,30}:map (L'|x| x + 1')
> = List{10,20,30}:map '|x| x + 1'
{11,21,31}

### Pros and Cons of Loopless Programming
Expand All @@ -254,7 +238,7 @@ then you have failed to express yourself clearly. Similarly, `ls:filter('>',0)`
will give you all the values in a list greater than zero. (Of course, if you
don't feel like using `List`, or have non-list-like tables, then `pl.tablex`
offers the same facilities. In fact, the `List` methods are implemented using
`tablex' functions.)
`tablex` functions.)

A common observation is that loopless programming is less efficient, particularly
in the way it uses memory. `ls1:map2('*',ls2):reduce '+'` will give you the dot
Expand Down Expand Up @@ -282,10 +266,9 @@ also takes a file object parameter, just like the C function.)

Splitting a string using a delimiter is a fairly common operation, hence `split`.

Utility functions like `is_callable` and `is_type` help with identifying what
kind of animal you are dealing with. Obviously, a function is callable, but an
object can be callable as well if it has overriden the `__call` metamethod. The
Lua `type` function handles the basic types, but can't distinguish between
Utility functions like `is_type` help with identifying what
kind of animal you are dealing with.
The Lua `type` function handles the basic types, but can't distinguish between
different kinds of objects, which are all tables. So `is_type` handles both
cases, like `is_type(s,"string")` and `is_type(ls,List)`.

Expand Down Expand Up @@ -339,11 +322,9 @@ whether the source is a binary chunk or text code (default is 'bt')
Using `utils.load` should reduce the need to call the deprecated function `setfenv`,
and make your Lua 5.1 code 5.2-friendly.

Currently, the `utils` module does define a global `getfenv` and `setfenv` for
Lua 5.2, based on code by Sergey Rozhenko. Note that these functions can fail
for functions which don't access any globals. (whether it's wise to directly
inject these functions into global or not, I'll leave for a later version to
decide)
The `utils` module exports `getfenv` and `setfenv` for
Lua 5.2 as well, based on code by Sergey Rozhenko. Note that these functions can fail
for functions which don't access any globals.

### Application Support

Expand All @@ -361,7 +342,7 @@ integer. Or you may specify upfront that some flags have associated values, and
then the values will follow the flag.

> require 'pl'
> flags,args = utils.parse_args({'-o','fred','-n10','fred.txt'},{o=true})
> flags,args = app.parse_args({'-o','fred','-n10','fred.txt'},{o=true})
> pretty.dump(flags)
{o='fred',n='10'}

Expand All @@ -380,10 +361,12 @@ private data, based on the script name. For example, `app.appfile "test.txt"`
from a script called `testapp.lua` produces the following file on my Windows
machine:

@plain
C:\Documents and Settings\SJDonova\.testapp\test.txt

and the equivalent on my Linux machine:

@plain
/home/sdonovan/.testapp/test.txt

If `.testapp` does not exist, it will be created.
Expand All @@ -400,7 +383,7 @@ Lua is similar to JavaScript in that the concept of class is not directly
supported by the language. In fact, Lua has a very general mechanism for
extending the behaviour of tables which makes it straightforward to implement
classes. A table's behaviour is controlled by its metatable. If that metatable
has a `__index` function or table, this will handle looking up anything which is
has a `\_\_index` function or table, this will handle looking up anything which is
not found in the original table. A class is just a table with an `__index` key
pointing to itself. Creating an object involves making a table and setting its
metatable to the class; then when handling `obj.fun`, Lua first looks up `fun` in
Expand Down Expand Up @@ -459,7 +442,7 @@ syntactic sugar, it is straightforward to implement classic object orientation.
> = leo:is_a(Cat)
true

All Animal does is define `__tostring`, which Lua will use whenever a string
All Animal does is define `\_\_tostring`, which Lua will use whenever a string
representation is needed of the object. In turn, this relies on `speak`, which is
not defined. So it's what C++ people would call an abstract base class; the
specific derived classes like Dog define `speak`. Please note that _if_ derived
Expand Down Expand Up @@ -536,7 +519,7 @@ multiple values) and `OrderedMap` (where the order of insertion is remembered.).
There is nothing special about these classes and you may inherit from them.

A powerful thing about dynamic languages is that you can redefine existing classes
and functions, which is often called 'monkey patching`. It's entertaining and convenient,
and functions, which is often called 'monkey patching' It's entertaining and convenient,
but ultimately anti-social; you may modify `List` but then any other modules using
this _shared_ resource can no longer be sure about its behaviour. (This is why you
must say `stringx.import()` explicitly if you want the extended string methods - it
Expand Down Expand Up @@ -627,13 +610,12 @@ when reading `mp.a`, first a check for an explicit _getter_ `get_a` and then onl
look for `_a`. Simularly, writing `mp.a` causes the _setter_ `set_a` to be used.

This is cool behaviour, but like much Lua metaprogramming, it is not free. Method
lookup on such objects goes through `__index` as before, but now `__index` is a
lookup on such objects goes through `\_\_index` as before, but now `\_\_index` is a
function which has to explicitly look up methods in the class, before doing any
property indexing, which is not going to be as fast as field lookup. If however,
your accessors actually do non-trivial things, then the extra overhead could be
worth it.

This is not really intended for _access control_ because external code can write
to `mp._a` directly. It is possible to have this kind of control in Lua, but it
again comes with run-time costs, and in this case a simple audit of code will
reveal any naughty use of 'protected' fields.
again comes with run-time costs.
2 changes: 1 addition & 1 deletion doc/manual/02-arrays.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ are fruits and colours but not both?'
[blue,green,apple,red,banana]

Adding elements to a set is simply `fruit['peach'] = true` and removing is
`fruit['apple'] = nil` . To make this simplicity properly, the `Set` class has no
`fruit['apple'] = nil` . To make this simplicity work properly, the `Set` class has no
methods - either you use the operator forms or explicitly use `Set.intersect`
etc. In this way we avoid the ambiguity that plagues `Map`.

Expand Down
9 changes: 6 additions & 3 deletions doc/manual/03-strings.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ easily at hand. Note that can be injected into the `string` table if you use
is preferrable. This is the recommended practice when writing modules for
consumption by other people, since it is bad manners to change the global state
of the rest of the system. Magic may be used for convenience, but there is always
a cost.
a price.


### String Templates
Expand Down Expand Up @@ -116,6 +116,9 @@ will also expand `$` variables using named fields:
> = '$animal[$num]' % {animal='dog',num=1}
dog[1]

As with `stringx.import` you have to do this explicitly, since all strings share the same
metatable. But in your own scripts you can feel free to do this.

### Another Style of Template

A new module is `template`, which is a version of Rici Lake's [Lua
Expand Down Expand Up @@ -149,8 +152,8 @@ and we get

There is a single function, `template.substitute` which is passed a template
string and an environment table. This table may contain some special fields,
like `_parent` which can be set to a table representing a 'fallback' environment
in case a symbol was not found. `_brackets` is usually '()' and `_escape` is
like `\_parent` which can be set to a table representing a 'fallback' environment
in case a symbol was not found. `\_brackets` is usually '()' and `\_escape` is
usually '#' but it's sometimes necessary to redefine these if the defaults
interfere with the target language - for instance, `$(V)` has another meaning in
Make, and `#` means a preprocessor line in C/C++.
Expand Down
7 changes: 3 additions & 4 deletions doc/manual/06-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Here is a simple Lua implementation:
-- property file parsing with Lua string patterns
props = []
for line in io.lines() do
if line:find('#,1,true) ~= 1 and not line:find('^%s*$') then
if line:find('#',1,true) ~= 1 and not line:find('^%s*$') then
local var,value = line:match('([^=]+)=(.*)')
props[var] = value
end
Expand Down Expand Up @@ -373,8 +373,7 @@ the actual iterator function which a query generates and dynamically compiles. B
using code generation, we can get pretty much optimal performance out of
arbitrary queries.

> lua -lpl -e "_DEBUG=true" -e "data.filter 'x,y where x > 4 sort by x'" <
test.txt
> lua -lpl -e "_DEBUG=true" -e "data.filter 'x,y where x > 4 sort by x'" < test.txt
return function (t)
local i = 0
local v
Expand Down Expand Up @@ -622,7 +621,7 @@ read a configuration from a string, use `stringio.open`.

Although Lua's string pattern matching is very powerful, there are times when
something more powerful is needed. `pl.lexer.scan` provides lexical scanners
which _tokenizes_ a string, classifying tokens into numbers, strings, etc.
which _tokenize_ a string, classifying tokens into numbers, strings, etc.

> lua -lpl
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
Expand Down
18 changes: 9 additions & 9 deletions doc/manual/07-functional.md
Original file line number Diff line number Diff line change
Expand Up @@ -354,22 +354,23 @@ values of a sequence or as a callback. Often useful functions have the wrong
number of arguments. So there is a need to construct a function of one argument
from one of two arguments, _binding_ the extra argument to a given value.

_currying_ takes a function of n arguments and returns a function of n-1
_partial application_ takes a function of n arguments and returns a function of n-1
arguments where the first argument is bound to some value:

> p2 = func.curry(print,'start>')
> p2 = func.bind1(print,'start>')
> p2('hello',2)
start> hello 2
> ops = require 'pl.operator'
> = tablex.filter({1,-2,10,-1,2},curry(ops.gt,0))
> = tablex.filter({1,-2,10,-1,2},bind1(ops.gt,0))
{-2,-1}
> tablex.filter({1,-2,10,-1,2},curry(ops.le,0))
> tablex.filter({1,-2,10,-1,2},bind1(ops.le,0))
{1,10,2}

The last example unfortunately reads backwards, because `curry` alway binds the
first argument!
The last example unfortunately reads backwards, because `bind1` alway binds the
first argument! Also unfortunately, in my youth I confused 'currying' with
'partial application', so the old name for `bind1` is `curry` - this alias still exists.

Currying is a specialized form of function argument binding. Here is another way
This is a specialized form of function argument binding. Here is another way
to say the `print` example:

> p2 = func.bind(print,'start>',func._1,func._2)
Expand All @@ -387,7 +388,6 @@ way around:
> tablex.filter({1,-2,10,-1,2},bind(ops.gt, _1, 0))
{1,10,2}


`tablex.merge` does a general merge of two tables. This example shows the
usefulness of binding the last argument of a function.

Expand All @@ -400,7 +400,7 @@ usefulness of binding the last argument of a function.
> = union(S1,S2)
{mary=24,jane=31,john=27,jones=50}

When using `bind` to curry `print`, we got a function of precisely two arguments,
When using `bind` with `print`, we got a function of precisely two arguments,
whereas we really want our function to use varargs like `print`. This is the role
of `_0`:

Expand Down
10 changes: 6 additions & 4 deletions doc/manual/08-additional.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,8 @@ command-line parsing easier and intuitive. It implements the standard GNU style,
i.e. short flags with one letter start with '-', and there may be an additional
long flag which starts with '--'. Generally options which take an argument expect
to find it as the next parameter (e.g. 'gcc test.c -o test') but single short
options taking a numerical parameter can dispense with the space (e.g. 'head -n4
test.c')
options taking a value can dispense with the space (e.g. 'head -n4
test.c' or `gcc -I/usr/include/lua/5.1 ...`)

As far as possible, Lapp will convert parameters into their equivalent Lua types,
i.e. convert numbers and convert filenames into file objects. If any conversion
Expand Down Expand Up @@ -436,8 +436,10 @@ argument.

If you'd like to use a multi-letter 'short' parameter you need to set
the `lapp.slack` variable to `true`.
In the following example we also see how default`false` and default`true` flags can be used
and how to overwrite the default `-h` help flag (`--help` still works fine).

In the following example we also see how default `false` and default `true` flags can be used
and how to overwrite the default `-h` help flag (`--help` still works fine) - this applies
to non-slack mode as well.

-- Parsing the command line ----------------------------------------------------
-- test.lua
Expand Down
8 changes: 4 additions & 4 deletions lua/pl/func.lua
Original file line number Diff line number Diff line change
Expand Up @@ -311,13 +311,13 @@ end
utils.add_function_factory(_PEMT,func.I)

--- bind the first parameter of the function to a value.
-- @class function
-- @name func.curry
-- @function func.bind1
-- @param fn a function of one or more arguments
-- @param p a value
-- @return a function of one less argument
-- @usage (curry(math.max,10))(20) == math.max(10,20)
func.curry = utils.bind1
-- @usage (bind1(math.max,10))(20) == math.max(10,20)
func.bind1 = utils.bind1
func.curry = func.bind1

--- create a function which chains two functions.
-- @param f a function of at least one argument
Expand Down
2 changes: 1 addition & 1 deletion lua/pl/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
-- (e.g. `utils.split`)
-- then that module is dynamically loaded. The submodules are all brought into
-- the global space.
--Updated to use pl.import_into
--Updated to use @{pl.import_into}
-- @module pl
require'pl.import_into'(_G)

Expand Down
2 changes: 1 addition & 1 deletion lua/pl/utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ end
-- @param p a value
-- @return a function such that f(x) is fn(p,x)
-- @raise same as @{function_arg}
-- @see pl.func.curry
-- @see func.bind1
function utils.bind1 (fn,p)
fn = utils.function_arg(1,fn)
return function(...) return fn(p,...) end
Expand Down
9 changes: 8 additions & 1 deletion run.lua
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ local function quote_if_needed (s)
return s
end

local function print_exit(msg)
print()
print(string.rep("*",#msg + 4))
print("* "..msg.." *")
print(string.rep("*",#msg + 4))
end

-- get the Lua command-line used to invoke this script
local cmd = app.lua()

Expand All @@ -17,7 +24,7 @@ function do_lua_files ()
print(cmd..' '..f)
local res,code = utils.execute(cmd..' '..f)
if not res then
print ('process failed with non-zero result: ['..code..'] '..f)
print_exit ('process failed with non-zero result: ['..code..'] '..f)
os.exit(1)
end
end
Expand Down

0 comments on commit d5f739d

Please sign in to comment.