Access outer variable inside a block and Y-combinator - lambda-calculus

I hope you all to be fine. I'm implementing the fixed-point Y-combinator in Harbour and I'm having some troubles with it. Well, the Y-combinator can be defined by the lambda-calculus as:
Y = (λh.λF.F(λ x.((h(h))(F))(x))) (λh.λF.F(λ x.((h(h))(F))(x)))
I'm trying to apply memoization with Y-combinator by performance questions. My current implementation is:
Function YMem( bF, aCache )
Local xAnswer
If !lCache ; lCache := { } ; EndIf
Return { |Arg| Iif( aCache[ Arg ] ;
, /* then */ aCache[ Arg ];
, /* otherwise */ aCache[ Arg ] := ;
Eval( Eval( bF, { |N| Eval( Eval( YMem, bF, aCache ), N ) } ), Arg ) ) }
Basically, I can't use statements inside blocks, but I can use expressions and it works just fine. I'm avoiding an infinite recursion and the limit going through by 0 to infinite.
Until this time, it compiles just fine, but when I'm trying to access a variable of an outer block, Harbour kicks me in Face!
To test the Y-combinator implementation, I try to apply a simple implemetation of fibonacci sequence, but when I return a block that receives a parameter G and implicitly returns a block that receives a parameter N, G becames unavailable for me and the compiler says me that "Outer codeblock variable is out of reach".
Function Main
Local bFib := YMem( { |G| ;
{ |N| ;
Iif( N == 0, 1, Iif( N == 1, 1, Eval( G, N - 1 ) + Eval( G, N - 2) ) );
} ;
} )
Return
This would also allow me to curry blocks. My question is: how can I access an outer variable inside a block, in Harbour?

In Harbour, Clipper and xBase-based programming languages, blocks never can refer
to the variable of the parent block. Blocks are not closures. We can reach that by
creating local storages and using them in the internal blocks:
Function TestOuterScope
Local accA
Local bAdd := { |A| accA := A, { |B| accA + B } }
Return Eval( Eval( bAdd, 10 ), 20 )

Related

Given: aabcdddeabb => Expected: [(a,2),(b,1),(c,1),(d,3),(e,1),(a,1),(b,1)] in Scala

I'm really interested in how this algorithm can be implemented. If possible, it would be great to see an implementation with and without recursion. I am new to the language so I would be very grateful for help. All I could come up with was this code and it goes no further:
print(counterOccur("aabcdddeabb"))
def counterOccur(string: String) =
string.toCharArray.toList.map(char => {
if (!char.charValue().equals(char.charValue() + 1)) (char, counter)
else (char, counter + 1)
})
I realize that it's not even close to the truth, I just don't even have a clue what else could be used.
First solution with using recursion. I take Char by Char from string and check if last element in the Vector is the same as current. If elements the same I update last element by increasing count(It is first case). If last element does not the same I just add new element to the Vector(second case). When I took all Chars from the string I just return result.
def counterOccur(string: String): Vector[(Char, Int)] = {
#tailrec
def loop(str: List[Char], result: Vector[(Char, Int)]): Vector[(Char, Int)] = {
str match {
case x :: xs if result.lastOption.exists(_._1.equals(x)) =>
val count = result(result.size - 1)._2
loop(xs, result.updated(result.size - 1, (x, count + 1)))
case x :: xs =>
loop(xs, result :+ (x, 1))
case Nil => result
}
}
loop(string.toList, Vector.empty[(Char, Int)])
}
println(counterOccur("aabcdddeabb"))
Second solution that does not use recursion. It works the same, but instead of the recursion it is using foldLeft.
def counterOccur2(string: String): Vector[(Char, Int)] = {
string.foldLeft(Vector.empty[(Char, Int)])((r, v) => {
val lastElementIndex = r.size - 1
if (r.lastOption.exists(lv => lv._1.equals(v))) {
r.updated(lastElementIndex, (v, r(lastElementIndex)._2 + 1))
} else {
r :+ (v, 1)
}
})
}
println(counterOccur2("aabcdddeabb"))
You can use a very simple foldLeft to accumulate. You also don't need toCharArray and toList because strings are implicitly convertible to Seq[Char]:
"aabcdddeabb".foldLeft(collection.mutable.ListBuffer[(Char,Int)]()){ (acc, elm) =>
acc.lastOption match {
case Some((c, i)) if c == elm =>
acc.dropRightInPlace(1).addOne((elm, i+1))
case _ =>
acc.addOne((elm, 1))
}
}
Here is a solution using foldLeft and a custom State case class:
def countConsecutives[A](data: List[A]): List[(A, Int)] = {
final case class State(currentElem: A, currentCount: Int, acc: List[(A, Int)]) {
def result: List[(A, Int)] =
((currentElem -> currentCount) :: acc).reverse
def nextState(newElem: A): State =
if (newElem == currentElem)
this.copy(currentCount = this.currentCount + 1)
else
State(
currentElem = newElem,
currentCount = 1,
acc = (this.currentElem -> this.currentCount) :: this.acc
)
}
object State {
def initial(a: A): State =
State(
currentElem = a,
currentCount = 1,
acc = List.empty
)
}
data match {
case a :: tail =>
tail.foldLeft(State.initial(a)) {
case (state, newElem) =>
state.nextState(newElem)
}.result
case Nil =>
List.empty
}
}
You can see the code running here.
One possibility is to use the unfold method. This method is defined for several collection types, here I'm using it to produce an Iterator (documented here for version 2.13.8):
def spans[A](as: Seq[A]): Iterator[Seq[A]] =
Iterator.unfold(as) {
case head +: tail =>
val (span, rest) = tail.span(_ == head)
Some((head +: span, rest))
case _ =>
None
}
unfold starts from a state and applies a function that returns, either:
None if we want to signal that the collection ended
Some of a pair that contains the next item of the collection we want to produce and the "remaining" state that will be fed to the next iteration.
In this example in particular, we start from a sequence of A called as (which can be a sequence of characters) and at each iteration:
if there's at least one item
we split head and tail
we further split the tail into the longest prefix that contains items equal to the head and the rest
we return the head and the prefix we got above as the next item
we return the rest of the collection as the state for the following iteration
otherwise, we return None as there's nothing more to be done
The result is a fairly flexible function that can be used to group together spans of equal items. You can then define the function you wanted initially in terms of this:
def spanLengths[A](as: Seq[A]): Iterator[(A, Int)] =
spans(as).map(a => a.head -> a.length)
This can be probably made more generic and its performance improved, but I hope this can be an helpful example about another possible approach. While folding a collection is a recursive approach, unfolding is referred to as a corecursive one (Wikipedia article).
You can play around with this code here on Scastie.
For
str = "aabcdddeabb"
you could extract matches of the regular expression
rgx = /(.)\1*/
to obtain the array
["aa", "b", "c", "ddd", "e", "a", "bb"]
and then map each element of the array to the desired string.1
def counterOccur(str: String): List[(Char, Int)] = {
"""(.)\1*""".r
.findAllIn(str)
.map(m => (m.charAt(0), m.length)).toList
}
counterOccur("aabcdddeabb")
#=> res0: List[(Char, Int)] = List((a,2), (b,1), (c,1), (d,3), (e,1), (a,1), (b,2))
The regular expression reads, "match any character and save it to capture group 1 ((.)), then match the content of capture group 1 zero or more times (\1*).
1. Scala code kindly provided by #Thefourthbird.

In pairs loop messed up

A normal working code but it doesn't work as i expected, seriously but wth Lua
local Exceptions = {1,2,3,5,7}
local mt = {__mod = function(v1, v2)
for i, v in pairs (v1) do
if v2 == v then
return true
else
return false
end
end
end }
setmetatable(Exceptions, mt)
print(Exceptions % 2)
v2 == v ( inside Exceptions has 2 so it should return true, but hell no, it returned false. This is annoying)
You break out of the pairs() loop when you return the result of v2 == v comparison.
The value of 2 is never reached, you exit the __mod function prematurely, reporting the result of comparing 1 and 2.
In your first loop run v2 is 2 and v is 1. As 2 ~= 1 you return false and that's it. No more iteration. Move return false after the loop.
local Exceptions = {1,2,3,5,7}
local mt = {__mod = function(v1, v2)
for i, v in pairs (v1) do
if v2 == v then
return true
end
end
return false
end }
setmetatable(Exceptions, mt)
print(Exceptions % 2)
Instead of
if v2 == v then
return true
else
return false
end
you could have simply written
return v2 == v
I personally would discourage altering the modulus operator for other things than calculating the modulus. I would have expected an element-wise modulus calcuation without seeing the implementation or any comment. Why not simply write a function isInTable(someTable, someNumber) that does the same? Same result, no confusion.

Mata error 3204

I am unsure why I am getting an error.
I think it may stem from a misunderstanding around the structure syntax, but I am not certain if this is the issue (it would be unsurprising if there are multiple issues).
I am emulating code (from William Gould's The Mata Book) in which the input is a scalar, but the input for the program I am writing is a colvector.
The objective of this exercise is to create a square matrix from a column vector (according to some rules) and once created, multiply this square matrix by itself.
The code is the following:
*! spatial_lag version 1.0.0
version 15
set matastrict on
//--------------------------------------------------------------
local SL struct laginfo
local RS real scalar
local RC real colvector
local RM real matrix
//--------------------------------------------------------------
mata
`SL'
{
//-------------------inputs:
`RC' v
//-------------------derived:
`RM' W
`RM' W2
`RS' n
}
void lagset(`RC' v)
{
`SL' scalar r
// Input:
r.v = v
//I set the derived variables to missing:
r.W = .z
r.W2 = .z
r.n = .z // length of vector V
}
`RM' w_mat(`SL' scalar r)
{
if (r.W == .z) {
real scalar row, i
real scalar col, j
r.W = J(r.n,r.n,0)
for (i=1; i<=r.n; i++) {
for (i=1; i<=r.n; i++) {
if (j!=i) {
if (r.v[j]==r.v[i]) {
r.W[i,j] = 1
}
}
}
}
}
return(r.W)
}
`RS' wlength(`SL' scalar r)
{
if (r.n == .z) {
r.n = length(r.v)
}
return(r.n)
}
`RM' w2mat(`SL' scalar r)
{
if (r.W2 == .z) {
r.W2 = r.W * r.W
}
return(r.W2)
}
end
This compiles without a problem, but it give an error when I attempt to use it interactively as follows:
y=(1\1\1\2\2\2)
q = lagset(y)
w_mat(q)
w2mat(q)
The first two lines run fine, but when I run the last two of those lines, I get:
w_mat(): 3204 q[0,0] found where scalar required
<istmt>: - function returned error
What am I misunderstanding?
This particular error is unrelated to structures. Stata simply complains because the lagset() function is void. That is, it does not return anything. Thus, q ends up being empty, which is in turn used as input in the function w_mat() inappropriately - hence the q[0,0] reference.

Lua: How can I concatenate methods, as with the string methods?

The string funtions can used with this ways:
string.FUNCTION('myString', PARAMETER)
or replace 'string' with the string to use and call it as method
('myString'):METHOD(PARAMETER)
The last way is very fine to read and allows to concatenate methods.
-- example string operation
some_str, pos = ' some string', 1
-- default string syntax
while string.find(string.sub(some_str, pos, pos), '%s') do pos = pos +1 end
-- the same with syntactic sugar
while some_str:sub(pos, pos):find('%s') do pos = pos +1 end
So I tried to get the same behaviour with my own functions. But this fails.
The only way I found, was to use an additional parameter to say: return the object itself or the result.
Here a simple example for this.
calc = {
result = 0,
operator = '',
run = function(self, a, b, r) -- return self with r='s'
if b == 's' then r, b = b, nil end
if not b then b, a = a, self.result end
if self.operator == '+' then self.result = (a) + (b)
elseif self.operator == '-' then self.result = (a) - (b)
elseif self.operator == '*' then self.result = (a) * (b)
elseif self.operator == '/' then self.result = (a) / (b) end
if r ~= nil then return self else return self.result end
end,
add = function(self, a, b, r) self.operator = '+' return self:run(a, b, r) end,
sub = function(self, a, b, r) self.operator = '-' return self:run(a, b, r) end,
mul = function(self, a, b, r) self.operator = '*' return self:run(a, b, r) end,
div = function(self, a, b, r) self.operator = '/' return self:run(a, b, r) end
}
-- single operation
result = calc:add(12, 5)
-- concatenated operations
result = calc:add(12, 5, 's'):sub(3, 's'):mul(2, 's'):div(7)
Exists any way to do it same like in string operations?
Thanks in advance.
Your subsequent calls assign 's' to b parameter, not to r. Of course check for return self fails. Rather than give different behaviour to methods with some flags make them always return self instead and make a separate method to return current result - it will be much cleaner to read and program.
After that your call will look like:
result = calc:new(12):add(5):sub(3):mul(2):div(7):result()
Also, you don't really need proxy functions that go into one big function that splits into ifs anyway - just do everything inside add/sub/mul/div themselves.
You'll probably want more than one calc object as well, with each one having its own separate current result. Store common functions in a metatable and make :new create new instances with this metatable and separate entry for result.
local calc_meta = { __index = {
add = function(self, number) self._r = self._r + number return self end,
sub = function(self, number) self._r = self._r - number return self end,
mul = function(self, number) self._r = self._r * number return self end,
div = function(self, number) self._r = self._r / number return self end,
result = function(self) return self._r end
}}
local calc = {
new = function(self, number)
return setmetatable({
_r = number or 0
}, calc_meta) end
}
result = calc:new(12):add(5):sub(3):mul(2):div(7):result()
print(result)
-- 4
You can't completely duplicate Lua's behavior with strings - it is built-in into VM to treat string table as metatable for string values and cannot be programmed without modifying VM itself. You can get rid of extra result at end though if you add __add/__sub and other numeric methods to metatable so they would automatically "unwrap" your object to basic number value. Of course you won't be able to apply your methods to "unwrapped" value after that.

pseudocode function to return two results for processing a tree

I'm trying to write a pseudocode for a recursive function that should process a binary tree. But the problem is that the function should return two variables. I know that functions are supposed to return on variable, and for more return values they should use list, array or vector, but I don't know how to present it as a pseudocode.
Does it look correct for a pseudocode?
function get_min(node *p)
begin
if (p==NULL) then
return list(0,0);
else
(vl,wl) = get_min(p->left)
(vr,wr) = get_min(p->right)
if (vl > vr) then
return list(vr + p->cost, 1)
else
return list(vl + p->cost, 0)
end if
end if
end function
Since it's pseudo-code, just about anything goes.
However, I'd rather go for omitting "list":
return (0, 0)
return (vr + p->cost, 1)
return (vl + p->cost, 0)
There doesn't seem to be any real benefit to putting "list" there - the (..., ...) format pretty clearly indicates returning two values already - there's no need to explicitly say you're returning them in a list.
Side note: You mention list, array or vector, but pair is another option in some languages, or wrapping the two in an object (typically giving the advantage of compile-time type checking - not really applicable in pseudo-code, obviously).
You could consider replacing "list" with "pair" instead of removing it if you wish to make it clear that the function only ever returns exactly 2 values.
If you pass parameters as reference , then there is no need to use lists as #Dukeling suggested .
void function get_min(node *p , int *cost , int * a)
begin
if (p==NULL) then
*cost =0 ; *a =0 ; return ;
else
get_min(p->left ,vl ,vw)
get_min(p->right , vr , wr)
if (vl > vr) then
*cost = vl + p->cost , *a =0 ; return;
else
*cost = vl + p->cost , *a =0 ; return ;
end if
end if
end function

Resources