Lexical Scoping vs Dynamic Scoping

In lexical scoping (and if you’re the interpreter), you search in the local function (the function which is running now), then you search in the function (or scope) in which that function was defined, then you search in the function (scope) in which that function was defined, and so forth. “Lexical” here refers to text, in that you can find out what variable is being referred to by looking at the nesting of scopes in the program text.

func A ()
{
   x  = 10
 
  func B()
   {
       print x
   }
}

In Dynamic scoping, by contrast, you search in the local function first, then you search in the function that called the local function, then you search in the function that called that function, and so on, up the call stack. “Dynamic” refers to change, in that the call stack can be different every time a given function is called, and so the function might hit different variables depending on where it is called from.

func A ()
{
   x  = 10
   call B()
}
func B()
{
    print x
}

Reference: http://c2.com/cgi/wiki?DynamicScoping

Posted in Lambda, Programming Languages Design | Leave a comment

The U-Combinator (Lambda Calculus)

Lambda calculus (also written as λ-calculus or called “the lambda calculus“) is a formal system in mathematical logic for expressing computation by way of variable binding and substitution. It was first formulated by Alonzo Church as a way to formalize mathematics through the notion of functions, in contrast to the field of set theory. Although not very successful in that respect, the lambda calculus found early successes in the area of computability theory (Wikipedia).

Image

(Alonzo Church)

If you are already familiar with lambdas in .net 3.5, python or scheme lambda is simply an anonymous function that doesn’t have a name can be returned or sent which is defined as a First-Class function.

Lambda Calculus notations can be used to describe computer programs for example let’s define :

  1.  λc.(void) means that we have a function that takes parameter c and returns nothing(void).
    if Conditions are formatted as (if test_condition then True_Part else False_Part) the true variable means passing the True_Part and the False_Part as a parameters and returning always the first which is the True_Part.
  2. true ≡ λc.λa.c(void)
  3. false ≡ λa.λc.a(void)
    Now the part which the article is talking about the U Combinator which is a very simple method to define recursion using lambdas.
  4.  U = λh.(h h)
    which is used in scheme as follows:
    (define (U f) (f f))
    (define (fact-nr f) (lambda (n) (if (zero? n) 1 (* n ((f f) (- n 1))))))
    when the function is called  ((U fact-nr) 3) will give the result 6.

Refrence:

http://okmij.org/ftp/Computation/fixed-point-combinators.html

Posted in Lambda, Programming Languages Design | Leave a comment

Functional Virtual Machine Interpreter (fvm)

Making a virtual machine that interprets the code generated from a functional programming language like scheme must apply more than one condition in Fvm i will consider set of certain properties in scheme which are:

1- Lexical Scoping.

2- Parameters binding.

3- First-Class functions ( Closures ).

so if i have the next example in scheme :

(define (print-var a b) (print (cons a b)))   //suppose function “print” takes a list and print there values

(print-var “hi” “ahmed”)

=> generated code will be like

  1. createe env
  2.    @params
  3.    @func
  4.        print-var, 7 //function name and code line defined in
  5. end
  6. define print-var
  7.    createe env2
  8.       @params a,b
  9.       @func
  10.    end
  11.    pop @param(a)
  12.    pop @param(b)
  13.    // calling a system function dosen’t need a frame to run in it
  14.    push a
  15.    push b
  16.    call-sys cons
  17.    // register (ac) for example will hold the returned value
  18.    push ac
  19.    call-sys print
  20. end
  21. // now to call the function (print-var “hi” “ahmed”) we create a frame
  22. createf frame
  23.    push “hi”
  24.    push “ahmed”
  25.    pushe env
  26.    call print-var
  27. end

—————————————–

inorder to call a function we create a frame where the function will run in it and we pass along the current environment if we are calling a function that isn’t a system defined because the passed environment will hold the lexical scoping rules.

for example : if print function calls sum before printing them

(define (print-var a b) (define (sum a b) (+ a b)) ….)

  1. define print-var
  2.    createe env2
  3.       @params a,b
  4.       @func sum, 8    //define sum is already in our current environment
  5.    end
  6.    pop @param(a)
  7.    pop @param(b)
  8.    define sum
  9.        createe env3
  10.          @params a,b
  11.          @func
  12.       end
  13.     pop @param(a)
  14.     pop @param(b)
  15.     push @param(x)
  16.     push @param(y)
  17.     call-sys plus
  18. end
  19.   …….

The important properties we had now is Lexical Scoping where each function defined in a certain scope calls a function in it’s first child scope must see it in it’s Environment and it pushes it’s environment to it when called.

Posted in Programming Languages Design, Talks | Tagged | Leave a comment

The Lexical Analyzer of “كلمات”

I started reading Kalimat code about 3 months ago and while reading it’s Lexical Analyzer trying to understand it’s way of implementing the FSM(Finite State Machine) i made a simple Overview of it’s Classes and the way of their interactions with each others, which you can find it here.

Hope it helps in Understanding the Lexical Analyzer structure of the Language, and waiting to read your feedback :).

Posted in C/C++, Programming Languages Design, كلمات | Leave a comment

The Arabic Programming Language “كلمات”

Kalimat is an educational programming language for Arabic-speaking children. It aims for readability and an easy to understand syntax while providing enough features to allow for complex, interesting and fun programs.

(screenshots) (online tutorial) (official site) (alternative download) (project roadmap)

A feature we consider somewhat unique to Kalimat is that it includes some very advanced capabilities while providing a smooth path to programming for the beginner. This article (in English) elaborates.

Language features

  • Beautiful, natural syntax
  • Both structured and object-oriented programming capabilities
  • Ability to create multifile programs with reusable ‘units’
  • Dynamically typed
  • Garbage collected
  • Concurrency via the CSP model (In progress)
  • FFI to interface to C libraries (In progress)

IDE Features

  • Color syntax highlighting
  • Tracing of running programs
  • Call stack visualization for running programs

Runtime features

  • Simple 2D graphics
  • Simple sprite engine with collision detection
  • Mouse and keyboard handling
  • GUI with an event model based on CSP (in progress)

You can read more and track this amazing project on Kalimat.

Posted in C/C++, Math & Algorithms, Programming Languages Design, كلمات | Leave a comment

Get all palindromes

Problem Definition:
given a string of length n check for all subsets of this string if the are
palindromes or not.

Problem Tackling Approach:
To solve this problem in a brute force way it will take about O(n^3) ,because it
will be something like this.

Algorithm 1:
For all char ‘a’ belongs to S do
For all char ‘b’ belongs S and after char ‘a’ do
Check_Palindrome(String(a,b))

This algorithm is doomed if it’s part in solving a bigger problem also if n grows large, but this algorithm showed a pattern here let’s look at this example.

Ex1:
Let our string here be “aaabbaaa”, when we apply Algorithm 1 you will notice the pattern when we apply function “Check_Palindromes” first to the string starting at index 0 to index 7 and to string at index 1 to index 6.
The Pattern is we checked if the substring from index 2 to 5 is palindrome twice!.

This pattern tells us we can divide it into small subsets and solve it with straight forward Dynammic Programming with O(n^2).

Algorithm 2:

for ( int spaces = 1; spaces < n; spaces++)
for(int startIndex = 0; startIndex < n && startIndex+spaces < n; startIndex++)
If( String[startIndex] == String[startIndex + spaces]   && DP[startIndex+1][spaces-1])
{
DP[startIndex][spaces] = true;
}

Ok, that’s all of it hope you find it challenging.

Problem Reference:
-idea of the problem taken from codechef Octobor 2010 contest.

Posted in C/C++, Math & Algorithms | 2 Comments

Introduction to Memory Management on iPhone

Content of this Article:

>Memory Management Model.

>How to allocate, retain and release Objects in Memory.

>Using nil to safe release Objects.

>References.

Memory Management Model in iOS dosen’t have a Garbage Collector inorder to increase the performance of the language on the mobile platform which is constrained to small computational power. Forthat it uses Reference Counting the idea of Reference Couting is very simple every object you define in the memory have a number that counts how many items reference this object, When it reaches zero the object is deallocated from the memory since no other object needs it.

Let’s take it to the Next Step Memory Allocation, to allocate an object we will use the keyword “alloc” and then call “init” to initialize the object, for Example:

NSString *string_1 = [[NSString alloc] init];

Now the reference count of the object is “1”, since alloc will allocate a memory block and makes it’s reference count to “1”. if another object referenced the same object the reference count wil increase by “1” (current reference count = 2) :

NSString *string_2 = [string_1 retain];

But after doing all these alloc and retain operations we are going to be faced with a huge problem which is Memory Leaks, objects tha aren’t needed or out of our scope will resides in the memory and won’t be garbage collected, Why ? Because there reference count isn’t “0”. Calling “release” every time on an object will decrease the reference count of the object by one.

[string_1 release]; //now reference count is “1”.

[string_1 release]; //now reference count is “0”, and the object will be deallocated.

since “nil” can be retained or released, by using this great advantage you can define a setter for your variable which will realese your object and assign it to nil. Why is that even useful ? It’s very helpful to not fail in an invalid pointer operation, for example:

-(void) setStr:(NSString *) input{
[input retain];
[myStr release];
myStr = input;
}

-(void) callFunction:(id)sender {
if(myStr)
//do something …..
else
//pointer assigned to null can't do anything …..
}

-(void) dealloc {
[self setStr:nil];
[super release];
}


References:

– Learning iPhone Programming

– Memory Management Basics Tutorial Video by Mark

Posted in Objective-C | Leave a comment

Linear Programming Model and it’s Applications

> Contents of the Article:

  • What is Linear Programming ?.
  • Applications of Linear Programming.
  • An Example.
  • Geometric Representation.
  • Refrences.

What is Linear Programming (LP) ? it is a mathematical method for determining a way to achieve the best outcome (such as maximum profit or lowest cost) in a given mathematical model for some list of requirements represented as linear relationships.

where x represents the vector of variables (to be determined), c and b are vectors of (known) coefficients and A is a (known) matrix of coefficients. The expression to be maximized or minimized is called the objective function (cTx in this case).

Applications of Linear Programming arose as a mathematical model developed during World War II to plan expenditures and returns in order to reduce costs to the army and increase losses to the enemy. It was kept secret until 1947. Postwar, many industries found its use in their daily planning.

The founders of the subject are Leonid Kantorovich, a Russian mathematician who developed linear programming problems in 1939, George B. Dantzig, who published the simplex method in 1947, and John von Neumann, who developed the theory of the duality in the same year.

Application in AI programming and in particular in Planning like LPSAT wich is used in Resource Planing. It is essentially a propositional conjunctive normal form(CNF) that includes linear (in)equalities as propositions. When SAT solver returns the propositions that are satisfiable the linear programming solver is used to get the value of the arithmetic (in)equalities.

An Example taken from Introduction to Algorithms named “A political problem”.

Problem: you are a politician trying to win the election. You have three districts Urban, Sub-Urban, Rureal. Each contains 100, 200, 50, registered vote. To win the elections your primary issues in your program are “build-roads”, “gun-control”, “farm-subsidies” and “gasoline-tax”.

Your researchers gave you a table for the effects of paying 1$ on each issue, how many votes you will win and how many will you lose for each urban.

Policy urban suburban rural
build-roads -2 5 3
gun-control 8 2 -5
farm-subsidies 0 0 10
gasoline-tax 10 0 -2

So inorder to win the election you decided that you need at least 50 votes, 100 votes, 25 votes respectively.

Solution Approach: let’s model each inequality

x1: amounts of dollars spent on “build-roads”

x2: amounts of dollars spent on “gun-control”

x3: amounts of dollars spent on “farm-subsidies”

x4: amounts of dollars spent on “gasoline-tax”

minimize x1 + x2 + x3 + x4

subject to

-2 * x1 + 8 * x2 + 0 * x3 + 10 * x4 >= 50 ( 1 )

5 * x1 + 2 * x2 + 0 * x3 + 0 * x4 >= 100 ( 2 )

3 * x1 + -5 * x2 +10 * x3 + -2 * x4 >= 25 ( 3 )

x1, x2, x3, x4 >= 0 ( 4 )

Geometric Representation is very important to understand linear programming more in depth, but inorder to be easy on geometric representation we will define another example with only two variables.

maximize x1 + x2

subject to

5 * x1 – 2 * x2 >= -2 ( 1 )

2 * x1 + x2 <= 10 ( 2 )

4 * x1 – x2 <= 8 ( 3 )

x1, x2 >= 0 ( 4 )

The Feasible area of solution is defined as the set of points that solve the 5 equations defined(shaded region).

References

Introduction to Algorithms(CLRS), 2nd edition (Chapter 29).

Wikipedia.

Posted in Math & Algorithms | Leave a comment

Introducing – “On-line Planning for Resource Production in RTS”

On-line Planning for Resource Production in Real-Time Strategy Games

Hei Chan, Alan Fern, Soumya Ray, Nick Wilson and Chris Ventura

School of Electrical Engineering and Computer Science

Oregon State University

Corvallis, OR 97330

{chanhe,afern,sray,wilsonic,ventura}@eecs.oregonstate.edu

 

Goal :

Develop action-selection mechanism in producing certain amount of resources as fast as possible.

Planner :

Computationally efficient “action-selection” mechanism which at each epoch creates a possibly Sub-Optimal concurrent plan from the current state to the goal, then begin executing the set of initial actions.

How it’s done :

formed via a combination of MEA(means-ends-analysis) and Scheduling and Bounded Search over sub-goals that aren’t required for goal achievements but may improve the make span.

Two Key problem domains :

-Resource production and tactical battles.

In Resource Production : player has to produce ( or gather ) varies raw materials, buildings, civilian and military Units to improve their economic and military power.

Tactical Battles : a player uses military units to gain territory and defeat enemy Units ( offensive or defensive actions ).

“Winning the Resource Production race is often a key factor in overall success”.

Uses :

1- either in computer opponent A.I.

2- Human can use it to specify resources needed and the Planner will get the best way to get this “RTS resource production is interesting from a pure A.I. Planning perspective as it encompasses a number of challenging issues”.

First, resource production involves temporal actions with numeric effects.

Second, performing well in this task requires highly concurrent activity.

Third, real-time constraints of the problem require action selection be computational efficient in a practical sense.

Why? :

Most existing planners are :

1- not handling temporal and numerical domains.

2- simply too inefficient to be useful.

3- produce highly Sub-Optimal plans.

The planning component used by online planner is based on a combination of means-ends analysis (MEA) and scheduling.

 

Given an initial state and resource goal, is used to compute a sequential plan that reaches the goal using the minimum number of actions and resources in sense that any valid plan must include all of the actions in the MEA plan.

Importantly, the special structure of our domain guarantees that MEA will produce such a plan and do so efficiently (linear time in the plan length).

Given the minimum sequential plan, we then reschedule those actions, allowing for concurrency, in an attempt to minimize the make span. This scheduling step is computationally hard, however, we have found that simple worst-case quadratic time heuristic methods work quite well. Thus both the MEA step and scheduling step are both low-order polynomial operations in the minimum number of actions required to achieve the goal, allowing for real-time efficiency.

Refrences :

MEA( means-ends analysis) : http://en.wikipedia.org/wiki/Means-ends_analysis

Posted in AI | Leave a comment

OCBP – “Introducing Darmok” part4

On-Line Plan Expansion and Execution

During execution, the plan expansion, plan execution and plan adaptation occur in parallel in order to maintain a current partial plan tree that the system is executing. A partial plan tree (or simply the “plan”) is represented as a tree consisting of two types of nodes: goals and snippets.

Initially, the plan consists of a single goal corresponding to the planning task at hand. In particular, in Darmok the initial goal is always “win the game”. Then, the plan expansion module asks the plan retrieval module to retrieve a snippet for that goal. That snippet might have several subgoals, for which the plan expansion module will again ask the plan retrieval module to retrieve snippets, and so on. For instance, at the top of Figure 8 we can see a sample plan, where the top goal is to “win”. The snippet assigned to the “win” goal has three subgoals, namely “build base”, “build army” and “attack”.

Figure 9 shows the algorithm the plan expansion module executes at every execution cycle given a plan p and a game state S. The plan expansion module is constantly querying the current plan to see if there is a ready open goal. When this happens, the open goal is sent to the plan retrieval module to retrieve a snippet for it. Then, that snippet is sent to the plan adaptation module, and then inserted in the current plan, marked as pending.

Function PlanExpansion(p, S)

G = GetReadyOpenGoals(p)

For g ∈ G Do

pg = RetrievePlan(g, S)

pg = AdaptPlan(pg , g, S)

p = InsertSnippetInPlan(p, g, pg )

EndFor

Return p

EndFunction

Figure 9: Plan expansion algorithm used in Darmok, where p is the current plan


Function PlanExecution(p, S)

p = startReadySnippets(p,S)

p = sendActionsToExecution(p,S)

p = updateSnippetStatus(p,S)

p = updateActionStatus(p,S)

Return p

EndFunction

Figure 10: Plan execution algorithm used in Darmok, where p is the current plan and S is the current game state.


Figure 10 shows the algorithm that the plan execution module executes at each execution cycle, composed of four steps:

• startReadySnippets: For each pending snippet, the execution module evaluates the preconditions, and as soon as they are met, the snippet starts its execution. If the current game state has changed since the time the and S is the current game state. plan retrieval module retrieved it, the snippet is handed back to the plan adaptation module to make sure that the plan is adequate for the current game state.

• sendActionsToExecution: If any of the executing snippets have any basic actions, and those actions have all its preconditions satisfied, then they are sent to Wargus to be executed. If the preconditions of the actions are not satisfied, the snippet is sent back to the plan adaptation module to see if the plan can be repaired. If after a certain amount of time t1 (set to 2000 game cycles in our experiments) it cannot, then the snippet is marked as failed, and thus its corresponding goal is open again (thus, the system will have to find another plan for that goal).

• updateSnippetStatus: The execution module periodically evaluates the alive conditions and success conditions of each snippet. If the alive conditions of an executing snippet are not satisfied, the snippet is marked as failed, and its goal is open again. If the success conditions of a snippet are satisfied, the snippet is marked as succeeded.

• updateActionStatus: Whenever a basic action succeeds or fails, the execution module updates the status of the snippet that contained it. When a basic action succeeds, the executing snippet can continue to the next step. When a basic action fails, the snippet is marked as failed, and thus its corresponding goal is open again.

Posted in AI | Leave a comment