函数美学3---Curry化

2019-05-19 10:40:36
收藏数:0
阅读数:180
评论数:0
  • Curry 化
  • 函数式编程
  • 了解一下函数式思维
#!/usr/bin/env lua


function deco(key)
   -- define decorator
   -- for currizing
    return function (f)
    return function (t)
        if t[key] then
            return f(t)
        else
            function g(s)
                t[key]=s
                return f(t)
            end
            return g
        end
    end
end
end

function reverse(tab)
    local ks = {}
    local N = #tab
    for i = 1, N do  
        ks[i]=table.remove(tab)
    end
    return ks
end

function decox(keys)
    -- powerful decorator
    local ks = reverse(keys)
    return function (f)
        for i, key in ipairs(ks) do
            f=deco(key)(f)
        end
        return f
    end
end


function f(t)
    s= 'hello word'
    for k, v in pairs(t) do
        s = string.format('<%s class=%s>' ..s..' </%s>', k, v, k)
    end
    return s
end


-- f {lala='lala', hehe='hehe'}

f = decox {'cat', 'you'} (f)
s = f {body='body', head='head'} 'animal' 'people'
print(s)