开发者

how do I implement functions with hidden arguments in functional programming?

I'm trying to learn functional programming using Lua. I have a Java background. I want to build a Chain using a recursive method. In Java I would do it somehow like this:

//Java
public Link buildChain() {
    return buildChain(null, 0, 100);
}


private Link buildChain(Link parentLink, int count, int length) {

    Link link = new Link();
    link.setParentLink(parentLink);
    if(count != length) {
        link.setChildLink(buildChain(link, count+1, length));
    }

    return link;
}

And obviously I'd have some class Link.

Now how would I implement this in a functional style? That class Link would be a table (in Lua), storing the parent and child link and whatever else a Link needs. But how would I do the two functions? Would I use a closure (though the private method doesn't use local variables of the public one) or a kind of inverted currying? Or just pattern 开发者_开发技巧matching?

Any tips and explanations would be very much appreciated. Oh, and I had a hard time finding a title for this question - if you have better idea, please say so.


I don't think there is anything 'functional' about this answer, but here is how I would do it in Lua. The 'id' field in each link is just there to provide a unique id:

function buildChain(link, cnt, len)
  cnt = cnt or some_global_default_cnt or 0
  len = len or some_global_default_len or 100
  link = link or { parent=nil, child=nil, id="Link " .. cnt }

  if cnt < len then 
    link.child = buildChain({parent=link, child=nil, id="Link " .. cnt+1 }, 
                            cnt+1, len)
  end

  return link 
end

n = buildChain()


Unsure of how the lua syntax is, but you have 2 options, depending on whether you want the worker function to be used in other contexts also or not.

If the worker function (the 2nd one) could be useful on its own, write 2 independent functions. Depending on the language, that may mean using 2 different names.

Or else, make the second function local to the first one, like in this haskelish code:

buildChain = worker [] 0 100 where
   worker parent count link = ....

It turns out that, at least in Haskell, buildChain is not really a function. This is also true for all other pure languages: because worker is called with 3 constant arguments, the result will always be the same.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜