tasks a-s

This commit is contained in:
Ingy döt Net 2013-04-10 23:57:08 -07:00
parent 47bf37c096
commit b83f433714
12433 changed files with 156208 additions and 123 deletions

View file

@ -0,0 +1,3 @@
Most programming languages offer support for [[Creating a function|subroutines]]. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it.

View file

@ -0,0 +1,2 @@
---
note: Basic language learning

View file

@ -0,0 +1,5 @@
package P is
... -- Declarations placed here are publicly visible
private
... -- These declarations are visible only to the children of P
end P;

View file

@ -0,0 +1,11 @@
package P is
type T is private; -- No components visible
procedure F (X : in out T); -- The only visible operation
N : constant T; -- A constant, which value is hidden
private
type T is record -- The implementation, visible to children only
Component : Integer;
end record;
procedure V (X : in out T); -- Operation used only by children
N : constant T := (Component => 0); -- Constant implementation
end P;

View file

@ -0,0 +1,4 @@
package body P is
-- The implementation of P, invisible to anybody
procedure W (X : in out T); -- Operation used only internally
end P;

View file

@ -0,0 +1,5 @@
private package P.Q is
... -- Visible to the siblings only
private
... -- Visible to the children only
end P.Q;

View file

@ -0,0 +1,25 @@
singleton = "global variable"
assume_global()
{
Global ; assume all variables declared in this function are global in scope
Static callcount := 0 ; except this one declared static, initialized once only
MsgBox % singleton ; usefull to initialize a bunch of singletons
callcount++
}
assume_global2()
{
Local var1 ; assume global except for var1 (similar to global scope declaration)
MsgBox % singleton
}
object(member, value = 0, null = 0)
{
Static ; assume all variables in this function to be static
If value ; can be used to simulate objects
_%member% := value
Else If null
_%member% := ""
Return (_%member%)
}

View file

@ -0,0 +1,33 @@
var1$ = "Global1"
var2$ = "Global2"
PRINT "Before function call:"
PRINT "var1$ = """ var1$ """"
PRINT "var2$ = """ var2$ """"
PROCtestscope(var1$)
PROCtestscope(var1$)
PRINT "After function call:"
PRINT "var1$ = """ var1$ """"
PRINT "var2$ = """ var2$ """"
END
DEF PROCtestscope(var2$)
PRINT "On entry to function:"
PRINT "var1$ = """ var1$ """"
PRINT "var2$ = """ var2$ """"
LOCAL var1$
PRIVATE var2$
PRINT "After LOCAL/PRIVATE:"
PRINT "var1$ = """ var1$ """"
PRINT "var2$ = """ var2$ """"
var1$ = "Local"
var2$ = "Private"
PRINT "After assignments:"
PRINT "var1$ = """ var1$ """"
PRINT "var2$ = """ var2$ """"
ENDPROC

View file

@ -0,0 +1,24 @@
int a; // a is global
static int p; // p is "locale" and can be seen only from file1.c
extern float v; // a global declared somewhere else
// a "global" function
int code(int arg)
{
int myp; // 1) this can be seen only from inside code
// 2) In recursive code this variable will be in a
// different stack frame (like a closure)
static int myc; // 3) still a variable that can be seen only from
// inside code, but its value will be kept
// among different code calls
// 4) In recursive code this variable will be the
// same in every stack frame - a significant scoping difference
}
// a "local" function; can be seen only inside file1.c
static void code2(void)
{
v = v * 1.02; // update global v
// ...
}

View file

@ -0,0 +1,8 @@
float v; // a global to be used from file1.c too
static int p; // a file-scoped p; nothing to share with static p
// in file1.c
int code(int); // this is enough to be able to use global code defined in file1.c
// normally these things go into a header.h
// ...

View file

@ -0,0 +1,12 @@
;; *bug* shall have a dynamic binding.
(declaim (special *bug*))
(let ((shape "triangle") (*bug* "ant"))
(flet ((speak ()
(format t "~% There is some ~A in my ~A!" *bug* shape)))
(format t "~%Put ~A in your ~A..." *bug* shape)
(speak)
(let ((shape "circle") (*bug* "cockroach"))
(format t "~%Put ~A in your ~A..." *bug* shape)
(speak))))

View file

@ -0,0 +1 @@
private

View file

@ -0,0 +1 @@
protected

View file

@ -0,0 +1 @@
public

View file

@ -0,0 +1 @@
protected

View file

@ -0,0 +1 @@
automated

View file

@ -0,0 +1,2 @@
strict private
strict protected

View file

@ -0,0 +1,5 @@
pi # private
pi = 3.14159
sum # private
sum x y = x + y

View file

@ -0,0 +1,6 @@
global var1 # used outside of procedures
procedure one() # a global procedure (the only kind)
local var2 # used inside of procedures
static var3 # also used inside of procedures
end

View file

@ -0,0 +1,17 @@
A=: 1
B=: 2
C=: 3
F=: verb define
A=:4
B=.5
D=.6
A+B+C+D
)
F ''
18
A
4
B
2
D
|value error

View file

@ -0,0 +1,35 @@
public //any class may access this member directly
protected //only this class, subclasses of this class,
//and classes in the same package may access this member directly
private //only this class may access this member directly
static //for use with other modifiers
//limits this member to one reference for the entire JVM
//adding no modifier (sometimes called "friendly") allows access to the member by classes in the same package
// Modifier | Class | Package | Subclass | World
// ------------|-------|---------|----------|-------
// public | Y | Y | Y | Y
// protected | Y | Y | Y | N
// no modifier | Y | Y | N | N
// private | Y | N | N | N
//method parameters are available inside the entire method
//Other declarations follow lexical scoping,
//being in the scope of the innermost set of braces ({}) to them.
//You may also create local scopes by surrounding blocks of code with braces.
public void function(int x){
//can use x here
int y;
//can use x and y here
{
int z;
//can use x, y, and z here
}
//can use x and y here, but NOT z
}

View file

@ -0,0 +1,15 @@
make "g 5 ; global
to proc :p
make "h 4 ; also global
local "l ; local, no initial value
localmake "m 3
sub 7
end
to sub :s
; can see :g, :h, and :s
; if called from proc, can also see :l and :m
localmake "h 5 ; hides global :h within this procedure and those it calls
end

View file

@ -0,0 +1,15 @@
OUTER
SET OUT=1,IN=0
WRITE "OUT = ",OUT,!
WRITE "IN = ",IN,!
DO INNER
WRITE:$DATA(OUT)=0 "OUT was destroyed",!
QUIT
INNER
WRITE "OUT (inner scope) = ",OUT,!
WRITE "IN (outer scope) = ",IN,!
NEW IN
SET IN=3.14
WRITE "IN (inner scope) = ",IN,!
KILL OUT
QUIT

View file

@ -0,0 +1,19 @@
Module -> localize names of variables (lexical scoping)
Block -> localize values of variables (dynamic scoping)
Module creates new symbols:
Module[{x}, Print[x];
Module[{x}, Print[x]]
]
->x$119
->x$120
Block localizes values only; it does not create new symbols:
x = 7;
Block[{x=0}, Print[x]]
Print[x]
->0
->7

View file

@ -0,0 +1,4 @@
my $lexical-variable;
our $package-variable;
state $persistent-lexical;
has $.public-attribute;

View file

@ -0,0 +1,13 @@
sub a {
my $*dyn = 'a';
c();
}
sub b {
my $*dyn = 'b';
c();
}
sub c {
say $*dyn;
}
a(); # says a
b(); # says b

View file

@ -0,0 +1,9 @@
use strict;
$x = 1; # Compilation error.
our $y = 2;
print "$y\n"; # Legal; refers to $main::y.
package Foo;
our $z = 3;
package Bar;
print "$z\n"; # Refers to $Foo::z.

View file

@ -0,0 +1,13 @@
package Foo;
my $fruit = 'apple';
package Bar;
print "$fruit\n"; # Prints "apple".
{
my $fruit = 'banana';
print "$fruit\n"; # Prints "banana".
}
print "$fruit\n"; # Prints "apple".
# The second $fruit has been destroyed.
our $fruit = 'orange';
print "$fruit\n"; # Prints "orange"; refers to $Bar::fruit.
# The first $fruit is inaccessible.

View file

@ -0,0 +1,10 @@
use 5.10.0;
sub count_up
{
state $foo = 13;
say $foo++;
}
count_up; # Prints "13".
count_up; # Prints "14".

View file

@ -0,0 +1,17 @@
our $camelid = 'llama';
sub phooey
{
print "$camelid\n";
}
phooey; # Prints "llama".
sub do_phooey
{
local $camelid = 'alpaca';
phooey;
}
do_phooey; # Prints "alpaca".
phooey; # Prints "llama".

View file

@ -0,0 +1,6 @@
$a = "foo" # global scope
function test {
$a = "bar" # local scope
Write-Host Local: $a # "bar" - local variable
Write-Host Global: $global:a # "foo" - global variable
}

View file

@ -0,0 +1,32 @@
;define a local integer variable by simply using it
baseAge.i = 10
;explicitly define local strings
Define person.s = "Amy", friend.s = "Susan"
;define variables that are both accessible inside and outside procedures
Global ageDiff = 3
Global extraYears = 5
Procedure test()
;define a local integer variable by simply using it
baseAge.i = 30
;explicitly define a local string
Define person.s = "Bob"
;allow access to a local variable in the main body of code
Shared friend
;create a local variable distinct from a variable with global scope having the same name
Protected extraYears = 2
PrintN(person + " and " + friend + " are " + Str(baseAge) + " and " + Str(baseAge + ageDiff + extraYears) + " years old.")
EndProcedure
If OpenConsole()
test()
PrintN(person + " and " + friend + " are " + Str(baseAge) + " and " + Str(baseAge + ageDiff + extraYears) + " years old.")
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf

View file

@ -0,0 +1,30 @@
>>> x="From global scope"
>>> def outerfunc():
x = "From scope at outerfunc"
def scoped_local():
x = "scope local"
return "scoped_local scope gives x = " + x
print(scoped_local())
def scoped_nonlocal():
nonlocal x
return "scoped_nonlocal scope gives x = " + x
print(scoped_nonlocal())
def scoped_global():
global x
return "scoped_global scope gives x = " + x
print(scoped_global())
def scoped_notdefinedlocally():
return "scoped_notdefinedlocally scope gives x = " + x
print(scoped_notdefinedlocally())
>>> outerfunc()
scoped_local scope gives x = scope local
scoped_nonlocal scope gives x = From scope at outerfunc
scoped_global scope gives x = From global scope
scoped_notdefinedlocally scope gives x = From global scope
>>>

View file

@ -0,0 +1,7 @@
X <- "global x"
f <- function() {
x <- "local x"
print(x) #"local x"
}
f() #prints "local x"
print(x) #prints "global x"

View file

@ -0,0 +1,5 @@
d <- data.frame(a=c(2,4,6), b = c(5,7,9))
attach(d)
b - a #success
detach(d)
b - a #produces error

View file

@ -0,0 +1,37 @@
x <- "global x"
print(x) #"global x"
local({ ## local({...}) is a shortcut for evalq({...}, envir=new.env())
## and is also equivalent to (function() {...})()
x <- "outer local x"
print(x) #"outer local x"
x <<- "modified global x"
print(x) #"outer local x" still
y <<- "created global y"
print(y) #"created global y"
local({
## Note, <<- is _not_ a global assignment operator. If an
## enclosing scope defines the variable, that enclosing scope gets
## the assignment. This happens in the order of evalution; a local
## variable may be defined later on in the same scope.
x <- "inner local x"
print(x) #"inner local x"
x <<- "modified outer local x"
print(x) #"inner local x"
y <<- "modified global y"
print(y) #"modified global y"
y <- "local y"
print(y) #"local y"
##this is the only way to reliably do a global assignment:
assign("x", "twice modified global x", globalenv())
print(evalq(x, globalenv())) #"twice modified global x"
})
print(x) #"modified outer local x"
})
print(x) #"twice modified global x"
print(y) #"modified global y"

View file

@ -0,0 +1,11 @@
x <- "global x"
f <- function() {
cat("Lexically enclosed x: ", x,"\n")
cat("Lexically enclosed x: ", evalq(x, parent.env(sys.frame())),"\n")
cat("Dynamically enclosed x: ", evalq(x, parent.frame()),"\n")
}
local({
x <- "local x"
f()
})

View file

@ -0,0 +1,12 @@
d <- data.frame(a=c(2,4,6), b = c(5,7,9))
also <- c(1, 0, 2)
with(d, mean(b - a + also)) #returns 4
## with() is built in, but you might have implemented it like this:
with.impl <- function(env, expr) {
env <- as.environment(env)
parent.env(env) <- parent.frame()
eval(substitute(expr), envir=env)
}
with.impl(d, mean(b - a + also))

View file

@ -0,0 +1,23 @@
/*REXX program to display scope modifiers (for subroutines/functions). */
a=1/4
b=20
c=3
d=5
call SSN_571 d**4
/* at this point, A is defined and equal to .25 */
/* at this point, B is defined and equal to 40 */
/* at this point, C is defined and equal to 27 */
/* at this point, D is defined and equal to 5 */
/* at this point, FF isn't defined. */
/* at this point, EWE is defined and equal to 'female sheep' */
/* at this point, G is defined and equal to 625 */
exit /*stick a fork in it, we're done.*/
/*─────────────────────────────────────SSN_571 submarine, er, subroutine*/
SSN_571: procedure expose b c ewe g; parse arg g
b = b*2
c = c**3
ff = b+c
ewe = 'female sheep'
d = 55555555
return /*compliments to Jules Verne's Captain Nemo? */

View file

@ -0,0 +1,3 @@
Local x
2 → x
Return x^x

View file

@ -0,0 +1,6 @@
@(maybe)@# perhaps this subclause suceeds or not
@ (block foo)
@ (bind a "a")
@ (accept foo)
@(end)
@(bind b "b")

View file

@ -0,0 +1,6 @@
@(maybe)@# perhaps this subclause suceeds or not
@ (block foo)
@ (bind a "a")
@ (fail foo)
@(end)
@(bind b "b")

View file

@ -0,0 +1,18 @@
set globalVar "This is a global variable"
namespace eval nsA {
variable varInA "This is a variable in nsA"
}
namespace eval nsB {
variable varInB "This is a variable in nsB"
proc showOff {varname} {
set localVar "This is a local variable"
global globalVar
variable varInB
namespace upvar ::nsA varInA varInA
puts "variable $varname holds \"[set $varname]\""
}
}
nsB::showOff globalVar
nsB::showOff varInA
nsB::showOff varInB
nsB::showOff localVar

View file

@ -0,0 +1,11 @@
oo::class create example {
# Note that this is otherwise syntactically the same as a local variable
variable objVar
constructor {} {
set objVar "This is an object variable"
}
method showOff {} {
puts "variable objVar holds \"$objVar\""
}
}
[example new] showOff

View file

@ -0,0 +1,4 @@
proc decr {varName {decrement 1}} {
upvar 1 $varName var
incr var [expr {-$decrement}]
}

View file

@ -0,0 +1,3 @@
proc semival args {
uplevel 1 [join $args ";"]
}

View file

@ -0,0 +1,15 @@
proc loop {varName from to body} {
upvar 1 $varName var
for {set var $from} {$var <= $to} {incr var} {
uplevel 1 $body
}
}
loop x 1 10 {
puts "x is now $x"
if {$x == 5} {
puts "breaking out..."
break
}
}
puts "done"

View file

@ -0,0 +1,11 @@
local_shop = 0
hidden_variable = 3
#library+
this_public_constant = local_shop
a_visible_function = +
#library-
for_local_people = 7

View file

@ -0,0 +1,10 @@
foo = 1
#hide+
foo = 2
bar = 3
#hide-
x = foo

View file

@ -0,0 +1,13 @@
foo = 1
#hide+
#export+
foo = 2
#export-
bar = 3
#hide-
x = foo

View file

@ -0,0 +1,4 @@
#import std
cat = 3
a_string = std-cat('foo','bar')