lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great Marcus Irven once stated:
> On Tue, Dec 8, 2009 at 10:44 AM, steve donovan <steve.j.donovan@gmail.com>wrote:
> 
> > On Mon, Dec 7, 2009 at 1:27 AM, Marcus Irven <marcus@marcusirven.com>
> > wrote:
> > > Announcing Underscore.lua -- http://mirven.github.com/underscore.lua/.
> > > Underscore.lua is a utility library with 30+ (and growing) functions that
> > > can be used in a functional or object-oriented manner.
> >
> > Nice, a well-chosen set of functionalities. I like how you've provided
> > some aliases.
> >
> > I quote:
> >
> > _.({1,2,3,4}):chain():map(function(i) return i+1
> > end):select(function(i) i%2 == 0 end):value()
> >
> > First random observation: Lua people tend to use '_' as a throwaway
> > variable, in cases like 'local _,i2 = s:find('%s+')'.  But it can
> > always be aliased if necessary.
> >
> >
> I thought of this as I use '_' for throwaway variables myself. I couldn't
> think of anything better though and since this is basically a rip off of the
> javascript library I went with it. Plus as you pointed out you can use "__ =
> _:no_conflict()" or whatever.
> 
> 
> > Second, support for 'string lambdas' would be cool:
> >
> > _.({1,2,3,4}):chain():map '|i| i + 1' :select '|i| i%2==0': value()
> >
> > There's a slight hit to compile them, but thereafter they can be
> > easily memoized. They don't require any syntax enhancements so David K
> > can only have style objections ;)
> >
> 
> This is an interesting idea, I'd have to either:
> 1) insert a 'return' so it would limit the string lambda to a single
> expression
> 2) have a complex parser
> 3) require the 'return' to be explicit (e.g. map '|i| return i + 1')

  Well ... I did play around with this idea:

	function h(line)
	  local f,e = loadstring(
	        string.format(
	                "return function(%s) return %s end",
	                string.match(line,"%|(.*)%|(.*)")
	        )
	  )
	  
	  if f == nil then
	    print(e)
	    return nil
	  end
	  
	  local g = f()
	  return g
	end
	
	function map(f,a)
	  result = {}  
	  for i = 1,#a do
	    result[i] = f(a[i])
	  end
	  return result
	end
	
	values  = { 1 , 2 , 3 , 4 , 5 }
	squares = map(h"|x| x * x",values)
	map(h"|x| print(x)",squares)
	1
	4
	9
	16
	25

Not terribly hard to do, but ... 

	function foo()
	  local v = { 1 , 2 , 3 , 4 , 5 }
	  local a = 4
	  local f = h"|x| x * a + 2"
	  local r = map(f,v)
	  
	  map(h"|x| print(x)",r)
	end

	foo()
	[string "return function(x) return  x * a + 2 end"]:1: attempt to perform
	arithmetic on global 'a' (a nil value) stack traceback:
	  [string "return function(x) return  x * a + 2 end"]:1: in function 'f'
	  stdin:4: in function 'map'
	  stdin:5: in function 'foo'
	  stdin:1: in main chunk
	  [C]: ?

So it's not perfect.  But hey, it was what?  All of ten minutes or so?

  -spc (It was easier to write than I thought actually ... )