lambdaway
::
counter2
7
|
list
|
login
|
load
|
|
_h1 [[counter]] | nested functions _ul [[https://rosettacode.org/wiki/Nested_function|https://rosettacode.org/wiki/Nested_function]] _p In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. _p Task: Write a program consisting of two nested functions that prints the following text. {pre 1. first 2. second 3. third } _ul The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. _ul The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. _h2 javascript {pre function makeList(separator) '{ var counter = 1; function makeItem(item) { return counter++ + separator + item + "\n"; } return makeItem("first") + makeItem("second") + makeItem("third"); } console.log(makeList(". ")); 1. first 2. second 3. third } _h2 lambdatalk {pre '{def makeList {def makeItem {lambda {:s :a :i} {div}{A.first {A.set! 0 {+ {A.first :a} 1} :a}}:s :i}} {lambda {:s} {S.map {{lambda {:s :a :i} {makeItem :s :a :i}} :s {A.new 0}} first second third }}} -> {def makeList {def makeItem {lambda {:s :a :i} {div}{A.first {A.set! 0 {+ {A.first :a} 1} :a}}:s :i}} {lambda {:s} {S.map {{lambda {:s :a :i} {makeItem :s :a :i}} :s {A.new 0}} first second third four }}} '{makeList .} -> {makeList .} '{def makeList2 {def makeItem2 {lambda {:a :i} {div}{A.first {A.set! 0 {+ {A.first :a} 1} :a}}* :i}} {lambda {:l} {S.map {{lambda {:a :i} {makeItem2 :a :i}} {A.new 0}} :l}}} -> {def makeList2 {def makeItem2 {lambda {:a :i} {div}{A.first {A.set! 0 {+ {A.first :a} 1} :a}}* :i}} {lambda {:l} {S.map {{lambda {:a :i} {makeItem2 :a :i}} {A.new 0}} :l }}} '{makeList2 first second third four five} -> {makeList2 first second third four five} }
lambdaway v.20211111