Re: A not stupid question (no questions are stupid)

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Re: A not stupid question (no questions are stupid)

RLak
>function change (src, find, rep)
>    src = gsub (src, "(%w+)", function (word)
>         if word == %find then
>              return %rep
>         else
>              return word
>         end
>    end)
>    return src
>end
>

Or:

function change(src, tab)
   src = gsub(src, "(%w+)", function(word) return tab[word] or word end)
   return src
end

src = change("this is the answer", {this = "these", is = "are", answer
= "answers"})

or even

function changer(tab)
   return function(src)
       src = gsub(src, "(%w+)", function(word) return %tab[word] or word
end)
   end
end

pluralise = changer {this = "these", is = "are", answer = "answers"}

src = pluralise(src)




Reply | Threaded
Open this post in threaded view
|

Re: A not stupid question (no questions are stupid)

Enrico Colombini
>function change(src, tab)
>   src = gsub(src, "(%w+)", function(word) return tab[word] or word end)
>   return src
>end
>
>src = change("this is the answer", {this = "these", is = "are", answer
>= "answers"})
>
>or even
>
>function changer(tab)
>   return function(src)
>       src = gsub(src, "(%w+)", function(word) return %tab[word] or word
>end)
>   end
>end
>
>pluralise = changer {this = "these", is = "are", answer = "answers"}
>
>src = pluralise(src)

Interesting. In fact, I already had my data (word-replacement pairs) in
such a table, so I could have avoided looping over the table as I did in my
program.

As for your intriguing second example, I am well aware of the power of
closures on the rational level (that is a closure over 'tab', right?), but
I still haven't reached the stage where I could use them without thinking
things over first (despite reading "The little lisper"). I suppose a bit of
exercise is in order.

  .Erix.