{"id":2464,"date":"2011-01-15T09:20:59","date_gmt":"2011-01-15T03:50:59","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=2464"},"modified":"2016-12-19T17:44:47","modified_gmt":"2016-12-19T12:14:47","slug":"curried-closures-in-groovy","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/curried-closures-in-groovy\/","title":{"rendered":"Curried Closures in groovy"},"content":{"rendered":"<p>There\u2019s a feature that adds spice to Groovy\u2014it\u2019s called <strong>Curried Closures<\/strong>.<br \/>\nThe term curry is taken from Haskell Curry, the mathematician who developed the concept of partial functions. Currying refers to taking multiple arguments into a function that takes many arguments, resulting in a new function that takes the remaining arguments and returns a result.<br \/>\nWhen we curry( ) a closure, we are asking the parameters to be prebound. That is, We are assigning value to the parameters of a closure. This can help remove redundancy or duplication in our code.<br \/>\nWhen calling the curry() method we need not supply the full complement of actual parameters. The curried call gives rise to the partial application of the closure. The partial application of a closure is another Closure object in which some values have been fixed.<br \/>\nFor Example:-<\/p>\n<pre lang=\"groovy\">\r\ndef tellFortunes(closure)\r\n{\r\nDate date = new Date(\"12\/16\/2010\" )\r\npostFortune = closure.curry(date) \r\n\/\/postFortune = {  fortune -> println \"Fortune for Thu Dec 16 00:00:00 UTC 2010 is '${fortune}'\"}\r\npostFortune \"This is the second parameter\"     \/\/ implicit call\r\npostFortune \"They're features, not bugs\"         \/\/ implicit call\r\n}\r\n\r\n\/\/Call tellFortunes with a closure\r\ntellFortunes() { date, fortune ->\r\nprintln \"Fortune for ${date} is '${fortune}'\"\r\n}\r\noutput:\r\nFortune for Thu Dec 16 00:00:00 UTC 2010 is 'This is the second parameter'\r\nFortune for Thu Dec 16 00:00:00 UTC 2010 is 'They're features, not bugs'\r\n<\/pre>\n<p>We have a function named tellFortunes that takes a closure. This closure has 2 parameters Date and fortune. Inside tellFortune Function we are prebound a closure parameter Date and assign it&#8217;s reference to a variable postFortune. Now we call postFortune with only 1 parameter which assign this value to the &#8220;fortune&#8221; parameter. <\/p>\n<p><strong>curry<\/strong>() assign values to the parameters from left to right. In order to assign the value from right to left we use <strong>rcurry<\/strong>() method.<br \/>\nFor Example:-<\/p>\n<pre lang=\"groovy\">\r\ndef divide = { a, b -> a \/ b }\r\ndef  assignValueToParameterStartFromRightPosition  = divide.rcurry(2)\r\nassignValueToParameterStartFromRightPosition(8)\r\noutput:\r\n4\r\nExample:\r\ndef sum = { a, b,c ->\r\nprintln \"a=\" + a\r\nprintln \"b=\" + b\r\nprintln \"c=\" + c\r\n}\r\ndef assignValueToParametersStartFromRightPosition = sum.rcurry(80,40)\r\nassignValueToParametersStartFromRightPosition(20)\r\noutput:\r\na=20\r\nb=80\r\nc=40\r\n<\/pre>\n<p>In order to support for Closure currying at a given index, we use <strong>ncurry<\/strong>() method. Parameters are supplied from index position &#8220;n&#8221;<br \/>\n(index start from 0).<br \/>\nBelow, we have a closure which is assigned to variable &#8220;divide&#8221;. Using <strong>ncurry<\/strong>() we assign the value to the parameter, which is at index &#8220;0&#8221;,in this case &#8220;a&#8221; is being assigned a value 80.<\/p>\n<pre lang=\"groovy\">\r\ndef divide = { a, b -> a \/ b }\r\ndef assignValueToParameterAtNthPosition = divide.ncurry(0,80)\r\nassignValueToParameterAtNthPosition(8)\r\noutput:\r\n10\r\nExample:\r\ndef printParameters = { a, b, c ->\r\nprintln \"a=\" + a\r\nprintln \"b=\" + b\r\nprintln \"c=\" + c\r\n}\r\ndef assignValueToParameterAtNthPosition = printParameters.ncurry(1,80)\r\nassignValueToParameterAtNthPosition(20,40)\r\noutput:\r\na=20\r\nb=80\r\nc=40\r\n<\/pre>\n<p><strong>Closure composition<\/strong><br \/>\nOne of the important characteristics of closures is composition, wherein you can define one closure whose purpose is to combine other closures. Using composition, two or more simple closures can be combined to produce a more elaborate one.<\/p>\n<pre lang=\"groovy\">\r\nExample:-\r\ndef multiply = { x, y -> return x * y }    \r\n\/\/ closure\r\ndef triple = multiply.curry(3)            \r\n\/\/ triple = { y -> return 3 * y }\r\ndef quadruple = multiply.curry(4) \r\n\/\/ quadruple = { y -> return 4 * y }\r\ndef composition = { f, g, x -> return f(g(x)) }\r\ndef twelveTimes = composition.curry(triple, quadruple)\r\ndef threeDozen = twelveTimes(3)\r\nprintln \"threeDozen: ${threeDozen}\"\t\t \r\n\/\/ threeDozen: 36\r\n<\/pre>\n<p><strong>Use-Case<\/strong>:<br \/>\nConsider the problem of computing the net price of a specific Book item, taking into account the shop discount and any governmental taxes such as a value added tax. If we include this logic as part of the Book class, the resulting solution would probably be a hard-wired one. Because the bookshop could change the value of its discount or apply it to only a selection of its stock, such a solution would likely be too rigid.<br \/>\nChanging such rules are readily accommodated using <strong>Curried Closures<\/strong>.<br \/>\nWe can use a set of simple closures to represent individual rules and then combine them in various ways using compositions. Finally, Map them to collections using computation patterns. <\/p>\n<pre lang=\"groovy\">\r\nclass Book {\r\n    String name\r\n    String author\r\n    BigDecimal price\r\n    String category\r\n}\r\n\r\ndef book = new Book(name:'Groovy', author:'KenB', price:25, category:'CompSci')\r\ndef discountRate = 0.1\r\ndef taxRate = 0.17\r\n\/\/  book closures\r\ndef rMultiply     = { y, x -> return x * y }\r\ndef calcDiscountedPrice = rMultiply.curry(1 - discountRate)\r\ndef calcTax = rMultiply.curry(1 + taxRate)\r\ndef composition   = { f, g, x -> return f(g(x)) }\r\ndef calcNetPrice = composition.curry(calcTax, calcDiscountedPrice)\r\n\/\/  now calculate net prices\r\ndef netPrice = calcNetPrice(bk.price)\r\nprintln \"netPrice: ${netPrice}\"\t\t\/\/ netPrice: 26.325\r\n<\/pre>\n<p>The closure rMultiply is a partial application that adapts the binary multiplication to be a unary closure by using a constant second operand. The two book closures calcDiscountedPrice and calcTax are instances of the rMultiply closure with set values for the multiplier value. The closure calcNetPrice is the algorithm to compute the net price by first calculating the discounted price and then the sales tax on top of that. Finally, calcNetPrice is applied to the price of the book.<\/p>\n<p>References:<br \/>\n<a href=\"http:\/\/www.ibm.com\/developerworks\/java\/library\/j-pg08235\/index.html\">http:\/\/www.ibm.com\/developerworks\/java\/library\/j-pg08235\/index.html<\/a><\/p>\n<p>Hope it helps!<\/p>\n<p>Gautam Malhotra<br \/>\ngautam@intelligrape.com<\/p>\n","protected":false},"excerpt":{"rendered":"<p>There\u2019s a feature that adds spice to Groovy\u2014it\u2019s called Curried Closures. The term curry is taken from Haskell Curry, the mathematician who developed the concept of partial functions. Currying refers to taking multiple arguments into a function that takes many arguments, resulting in a new function that takes the remaining arguments and returns a result. [&hellip;]<\/p>\n","protected":false},"author":25,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":4},"categories":[7],"tags":[478,479,9],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/2464"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/25"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=2464"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/2464\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=2464"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=2464"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=2464"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}