Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

@ -0,0 +1,2 @@
---
from: http://rosettacode.org/wiki/Multiple_distinct_objects

View file

@ -0,0 +1,13 @@
Create a [[sequence]] (array, list, whatever) consisting of <var>n</var> distinct, initialized items of the same type. <var>n</var> should be determined at runtime.
By ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. <tt>calloc()</tt> or <tt>int a[n] = {};</tt> in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of <var>n</var> references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: [[Closures/Value capture]]
<br><br>

View file

@ -0,0 +1 @@
(1..n).map(i -> Foo())

View file

@ -0,0 +1,8 @@
MODE FOO = STRUCT(CHAR u,l);
INT n := 26;
[n]FOO f;
# Additionally each item can be initialised #
FOR i TO UPB f DO f[i] := (REPR(ABS("A")-1+i), REPR(ABS("a")-1+i)) OD;
print((f, new line))

View file

@ -0,0 +1,24 @@
begin
record T ( integer n, m );
reference(T) singleT;
integer numberOfElements;
singleT := T( 0, 0 );
numberOfElements := 3;
begin
reference(T) array tArray ( 1 :: numberOfElements );
% initialise the "right" way %
for i := 1 until numberOfElements do begin
tArray( i ) := T( i, i * 2 );
m(tArray( i )) := m(tArray( i )) + 1;
end for_i ;
write();
for i := 1 until numberOfElements do writeon( i_w := 1, s_w := 0, n(tArray( i )), ", ", m(tArray( i )), "; " );
% initialise the "wrong" way %
for i := 1 until numberOfElements do begin
tArray( i ) := singleT;
m(tArray( i )) := m(tArray( i )) + 1;
end for_i ;
write();
for i := 1 until numberOfElements do writeon( i_w := 1, s_w := 0, n(tArray( i )), ", ", m(tArray( i )), "; " )
end
end.

View file

@ -0,0 +1,57 @@
DEFINE PTR="CARD"
DEFINE OBJSIZE="4"
TYPE Record=[BYTE b CHAR c INT i]
PROC PrintObjects(PTR ARRAY items BYTE count)
Record POINTER r
BYTE n
FOR n=0 TO count-1
DO
r=items(n)
PrintF("(%B ""%C"" %I) ",r.b,r.c,r.i)
IF n MOD 3=2 THEN PutE() FI
OD
PutE()
RETURN
PROC Main()
DEFINE MIN="1"
DEFINE MAX="20"
DEFINE BUFSIZE="80"
BYTE ARRAY buffer(BUFSIZE)
PTR ARRAY items(MAX)
BYTE count=[0],n,LMARGIN=$52,oldLMARGIN
Record POINTER r
oldLMARGIN=LMARGIN
LMARGIN=0 ;remove left margin on the screen
Put(125) PutE() ;clear the screen
WHILE count<min OR count>max
DO
PrintF("How many objects (%I-%I)?",MIN,MAX)
count=InputB()
OD
FOR n=0 TO count-1
DO
items(n)=buffer+n*OBJSIZE
OD
PutE()
PrintE("Uninitialized objects:")
PrintObjects(items,count)
FOR n=0 TO count-1
DO
r=items(n)
r.b=n r.c=n+'A r.i=-n
OD
PutE()
PrintE("Initialized objects:")
PrintObjects(items,count)
LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN

View file

@ -0,0 +1 @@
A : array (1..N) of T;

View file

@ -0,0 +1 @@
A : array (1..N) of T := (others => V);

View file

@ -0,0 +1 @@
(1..N => V)

View file

@ -0,0 +1,58 @@
void
show_sublist(list l)
{
integer i, v;
for (i, v in l) {
o_space(sign(i));
o_integer(v);
}
}
void
show_list(list l)
{
integer i;
list v;
for (i, v in l) {
o_text(" [");
show_sublist(v);
o_text("]");
}
o_byte('\n');
}
list
multiple_distinct(integer n, object o)
{
list l;
call_n(n, l_append, l, o);
return l;
}
integer
main(void)
{
list l, z;
# create a list of integers - `3' will serve as initializer
l = multiple_distinct(8, 3);
l_clear(l);
# create a list of distinct lists - `z' will serve as initializer
l_append(z, 4);
l = multiple_distinct(8, z);
# modify one of the sublists
l_q_list(l, 3)[0] = 7;
# display the list of lists
show_list(l);
return 0;
}

View file

@ -0,0 +1,60 @@
-- MULTIPLE DISTINCT OBJECTS -------------------------------------------------
-- nObjects Constructor -> Int -> [Object]
on nObjects(f, n)
map(f, enumFromTo(1, n))
end nObjects
-- TEST ----------------------------------------------------------------------
on run
-- someConstructor :: a -> Int -> b
script someConstructor
on |λ|(_, i)
{index:i}
end |λ|
end script
nObjects(someConstructor, 6)
--> {{index:1}, {index:2}, {index:3}, {index:4}, {index:5}, {index:6}}
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn

View file

@ -0,0 +1 @@
{{index:1}, {index:2}, {index:3}, {index:4}, {index:5}, {index:6}}

View file

@ -0,0 +1,3 @@
a := []
Loop, %n%
a[A_Index] := new Foo()

View file

@ -0,0 +1,17 @@
REM Determine object count at runtime:
n% = RND(1000)
REM Declare an array of structures; all members are initialised to zero:
DIM objects{(n%) a%, b$}
REM Initialise the objects to distinct values:
FOR i% = 0 TO DIM(objects{()},1)
objects{(i%)}.a% = i%
objects{(i%)}.b$ = STR$(i%)
NEXT
REM This is how to create an array of pointers to the same object:
DIM objects%(n%), object{a%, b$}
FOR i% = 0 TO DIM(objects%(),1)
objects%(i%) = object{}
NEXT

View file

@ -0,0 +1 @@
n.of foo.new

View file

@ -0,0 +1 @@
n.of { foo.new }

View file

@ -0,0 +1,9 @@
// this assumes T is a default-constructible type (all built-in types are)
T* p = new T[n]; // if T is POD, the objects are uninitialized, otherwise they are default-initialized
//If default initialisation is not what you want, or if T is a POD type which will be uninitialized
for(size_t i = 0; i != n; ++i)
p[i] = make_a_T(); //or some other expression of type T
// when you don't need the objects any more, get rid of them
delete[] p;

View file

@ -0,0 +1,12 @@
#include <vector>
#include <algorithm>
#include <iterator>
// this assumes T is default-constructible
std::vector<T> vec1(n); // all n objects are default-initialized
// this assumes t is a value of type T (or a type which implicitly converts to T)
std::vector<T> vec2(n, t); // all n objects are copy-initialized with t
// To initialise each value differently
std::generate_n(std::back_inserter(vec), n, makeT); //makeT is a function of type T(void)

View file

@ -0,0 +1,22 @@
#include <vector>
#include <tr1/memory>
using namespace std;
using namespace std::tr1;
typedef shared_ptr<T> TPtr_t;
// the following is NOT correct:
std::vector<TPtr_t > bvec_WRONG(n, p); // create n copies of p, which all point to the same opject p points to.
// nor is this:
std::vector<TPtr_t> bvec_ALSO_WRONG(n, TPtr_t(new T(*p)) ); // create n pointers to a single copy of *p
// the correct solution
std::vector<TPtr_t > bvec(n);
for (int i = 0; i < n; ++i)
bvec[i] = TPtr_t(new T(*p); //or any other call to T's constructor
// another correct solution
// this solution avoids uninitialized pointers at any point
std::vector<TPtr_t> bvec2;
for (int i = 0; i < n; ++i)
bvec2.push_back(TPtr_t(new T(*p));

View file

@ -0,0 +1,5 @@
using System;
using System.Linq;
using System.Collections.Generic;
List<Foo> foos = Enumerable.Range(1, n).Select(x => new Foo()).ToList();

View file

@ -0,0 +1,3 @@
foo *foos = malloc(n * sizeof(*foos));
for (int i = 0; i < n; i++)
init_foo(&foos[i]);

View file

@ -0,0 +1,5 @@
user> (take 3 (repeat (rand))) ; repeating the same random number three times
(0.2787011365537204 0.2787011365537204 0.2787011365537204)
user> (take 3 (repeatedly rand)) ; creating three different random number
(0.8334795669220695 0.08405601245793926 0.5795448744634744)
user>

View file

@ -0,0 +1,2 @@
(make-list n :initial-element (make-the-distinct-thing))
(make-array n :initial-element (make-the-distinct-thing))

View file

@ -0,0 +1 @@
(loop repeat n collect (make-the-distinct-thing))

View file

@ -0,0 +1,2 @@
(map-into (make-list n) #'make-the-distinct-thing)
(map-into (make-array n) #'make-the-distinct-thing)

View file

@ -0,0 +1,3 @@
auto fooArray = new Foo[n];
foreach (ref item; fooArray)
item = new Foo();

View file

@ -0,0 +1,2 @@
auto barArray = new Bar[n];
barArray[] = initializerValue;

View file

@ -0,0 +1,10 @@
var
i: Integer;
lObject: TMyObject;
lList: TObjectList<TMyObject>;
begin
lList := TObjectList<TMyObject>.Create;
lObject := TMyObject.Create;
for i := 1 to 10 do
lList.Add(lObject);
// ...

View file

@ -0,0 +1,8 @@
var
i: Integer;
lList: TObjectList<TMyObject>;
begin
lList := TObjectList<TMyObject>.Create;
for i := 1 to 10 do
lList.Add(TMyObject.Create);
// ...

View file

@ -0,0 +1,4 @@
pragma.enable("accumulator")
...
accum [] for _ in 1..n { _.with(makeWhatever()) }

View file

@ -0,0 +1,15 @@
;; wrong - make-vector is evaluated one time - same vector
(define L (make-list 3 (make-vector 4)))
L → (#(0 0 0 0) #(0 0 0 0) #(0 0 0 0))
(vector-set! (first L ) 1 '🔴) ;; sets the 'first' vector
L → (#(0 🔴 0 0) #(0 🔴 0 0) #(0 🔴 0 0))
;; right - three different vectors
(define L(map make-vector (make-list 3 4)))
L → (#(0 0 0 0) #(0 0 0 0) #(0 0 0 0))
(vector-set! (first L ) 1 '🔵) ;; sets the first vector
L → (#(0 🔵 0 0) #(0 0 0 0) #(0 0 0 0)) ;; OK

View file

@ -0,0 +1,14 @@
import system'routines;
import extensions;
class Foo;
// create a list of disting object
fill(n)
= RangeEnumerator.new(1,n).selectBy:(x => new Foo()).toArray();
// testing
public program()
{
var foos := fill(10);
}

View file

@ -0,0 +1 @@
randoms = for _ <- 1..10, do: :rand.uniform(1000)

View file

@ -0,0 +1,5 @@
>List.replicate 3 (System.Guid.NewGuid());;
val it : Guid list =
[485632d7-1fd6-4d9e-8910-7949d7b2b485; 485632d7-1fd6-4d9e-8910-7949d7b2b485;
485632d7-1fd6-4d9e-8910-7949d7b2b485]

View file

@ -0,0 +1,5 @@
> List.init 3 (fun _ -> System.Guid.NewGuid());;
val it : Guid list =
[447acb0c-092e-4f85-9c3a-d369e4539dae; 5f41c04d-9bc0-4e96-8165-76b41fe8cd93;
1086400c-72ff-4763-9bb9-27e17bd4c7d2]

View file

@ -0,0 +1 @@
1000 [ { 1 } clone ] replicate

View file

@ -0,0 +1,23 @@
include FMS-SI.f
include FMS-SILib.f
\ create a list of VAR objects the right way
\ each: returns a unique object reference
o{ 0 0 0 } dup p: o{ 0 0 0 }
dup each: drop . 10774016
dup each: drop . 10786896
dup each: drop . 10786912
\ create a list of VAR objects the wrong way
\ each: returns the same object reference
var x
object-list2 list
x list add:
x list add:
x list add:
list p: o{ 0 0 0 }
list each: drop . 1301600
list each: drop . 1301600
list each: drop . 1301600

View file

@ -0,0 +1,42 @@
program multiple
! Define a simple type
type T
integer :: a = 3
end type T
! Define a type containing a pointer
type S
integer, pointer :: a
end type S
type(T), allocatable :: T_array(:)
type(S), allocatable :: S_same(:)
integer :: i
integer, target :: v
integer, parameter :: N = 10
! Create 10
allocate(T_array(N))
! Set the fifth one to b something different
T_array(5)%a = 1
! Print them out to show they are distinct
write(*,'(10i2)') (T_array(i),i=1,N)
! Create 10 references to the same object
allocate(S_same(N))
v = 5
do i=1, N
allocate(S_same(i)%a)
S_same(i)%a => v
end do
! Print them out - should all be 5
write(*,'(10i2)') (S_same(i)%a,i=1,N)
! Change the referenced object and reprint - should all be 3
v = 3
write(*,'(10i2)') (S_same(i)%a,i=1,N)
end program multiple

View file

@ -0,0 +1 @@
dim as foo array(1 to n)

View file

@ -0,0 +1,7 @@
func nxm(n, m int) [][]int {
d2 := make([][]int, n)
for i := range d2 {
d2[i] = make([]int, m)
}
return d2
}

View file

@ -0,0 +1,8 @@
func nxm(n, m int) [][]int {
d1 := make([]int, m)
d2 := make([][]int, n)
for i := range d2 {
d2[i] = d1
}
return d2
}

View file

@ -0,0 +1 @@
def createFoos1 = { n -> (0..<n).collect { new Foo() } }

View file

@ -0,0 +1,2 @@
// Following fails, creates n references to same object
def createFoos2 = {n -> [new Foo()] * n }

View file

@ -0,0 +1,13 @@
[createFoos1, createFoos2].each { createFoos ->
print "Objects distinct for n = "
(2..<20).each { n ->
def foos = createFoos(n)
foos.eachWithIndex { here, i ->
foos.eachWithIndex { there, j ->
assert (here == there) == (i == j)
}
}
print "${n} "
}
println()
}

View file

@ -0,0 +1 @@
replicateM n makeTheDistinctThing

View file

@ -0,0 +1 @@
mapM makeTheDistinctThing [1..n]

View file

@ -0,0 +1,2 @@
do x <- makeTheDistinctThing
return (replicate n x)

View file

@ -0,0 +1,7 @@
items_wrong := list (10, [])
# prints '0' for size of each item
every item := !items_wrong do write (*item)
# after trying to add an item to one of the lists
push (items_wrong[1], 2)
# now prints '1' for size of each item
every item := !items_wrong do write (*item)

View file

@ -0,0 +1,2 @@
items := list(10)
every i := 1 to 10 do items[i] := []

View file

@ -0,0 +1 @@
i.

View file

@ -0,0 +1,2 @@
i. 4
0 1 2 3

View file

@ -0,0 +1,7 @@
Foo[] foos = new Foo[n]; // all elements initialized to null
for (int i = 0; i < foos.length; i++)
foos[i] = new Foo();
// incorrect version:
Foo[] foos_WRONG = new Foo[n];
Arrays.fill(foos, new Foo()); // new Foo() only evaluated once

View file

@ -0,0 +1,6 @@
List<Foo> foos = new ArrayList<Foo>();
for (int i = 0; i < n; i++)
foos.add(new Foo());
// incorrect:
List<Foo> foos_WRONG = Collections.nCopies(n, new Foo()); // new Foo() only evaluated once

View file

@ -0,0 +1,17 @@
public static <E> List<E> getNNewObjects(int n, Class<? extends E> c){
List<E> ans = new LinkedList<E>();
try {
for(int i=0;i<n;i++)
ans.add(c.newInstance());//can't call new on a class object
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return ans;
}
public static List<Object> getNNewObjects(int n, String className)
throws ClassNotFoundException{
return getNNewObjects(n, Class.forName(className));
}

View file

@ -0,0 +1,3 @@
var a = new Array(n);
for (var i = 0; i < n; i++)
a[i] = new Foo();

View file

@ -0,0 +1,14 @@
(n => {
let nObjects = n => Array.from({
length: n + 1
}, (_, i) => {
// optionally indexed object constructor
return {
index: i
};
});
return nObjects(6);
})(6);

View file

@ -0,0 +1,2 @@
[{"index":0}, {"index":1}, {"index":2}, {"index":3},
{"index":4}, {"index":5}, {"index":6}]

View file

@ -0,0 +1,19 @@
def Array(atype; n):
if atype == "number" then [ range(0;n) ]
elif atype == "object" then [ range(0;n)| {"value": . } ]
elif atype == "array" then [ range(0;n)| [.] ]
elif atype == "string" then [ range(0;n)| tostring ]
elif atype == "boolean" then
if n == 0 then [] elif n == 1 then [false] elif n==2 then [false, true]
else error("there are only two boolean values")
end
elif atype == "null" then
if n == 0 then [] elif n == 1 then [null]
else error("there is only one null value")
end
else error("\(atype) is not a jq type")
end;
# Example:
Array("object"; 4)

View file

@ -0,0 +1,2 @@
foo() = rand() # repeated calls change the result with each call
repeat([foo()], outer=5) # but this only calls foo() once, clones that first value

View file

@ -0,0 +1 @@
[foo() for i in 1:5] # Code this to call the function within each iteration

View file

@ -0,0 +1,26 @@
// version 1.1.2
class Foo {
val id: Int
init {
id = ++numCreated // creates a distict id for each object
}
companion object {
private var numCreated = 0
}
}
fun main(args: Array<String>) {
val n = 3 // say
/* correct approach - creates references to distinct objects */
val fooList = List(n) { Foo() }
for (foo in fooList) println(foo.id)
/* incorrect approach - creates references to same object */
val f = Foo()
val fooList2 = List(n) { f }
for (foo in fooList2) println(foo.id)
}

View file

@ -0,0 +1 @@
arr := n times to (Array) map { Object clone. }.

View file

@ -0,0 +1,4 @@
;; Will print 10 distinct, arbitrary numbers.
arr visit {
Kernel id printObject.
}.

View file

@ -0,0 +1,8 @@
| ?- create_protocol(statep, [], [public(state/1)]),
findall(
Id,
(integer::between(1, 10, N),
create_object(Id, [implements(statep)], [], [state(N)])),
Ids
).
Ids = [o1, o2, o3, o4, o5, o6, o7, o8, o9, o10].

View file

@ -0,0 +1,8 @@
| ?- create_object(state, [instantiates(state)], [public(state/1)], [state(0)]),
findall(
Id,
(integer::between(1, 10, N),
create_object(Id, [instantiates(state)], [], [state(N)])),
Ids
).
Ids = [o1, o2, o3, o4, o5, o6, o7, o8, o9, o10].

View file

@ -0,0 +1,17 @@
-- This concept is relevant to tables in Lua
local table1 = {1,2,3}
-- The following will create a table of references to table1
local refTab = {}
for i = 1, 10 do refTab[i] = table1 end
-- Instead, tables should be copied using a function like this
function copy (t)
local new = {}
for k, v in pairs(t) do new[k] = v end
return new
end
-- Now we can create a table of independent copies of table1
local copyTab = {}
for i = 1, 10 do copyTab[i] = copy(table1) end

View file

@ -0,0 +1,41 @@
Module CheckIt {
Form 60, 40
Foo=Lambda Id=1 (m)->{
class Alfa {
x, id
Class:
Module Alfa(.x, .id) {}
}
=Alfa(m, id)
id++
}
Dim A(10)<<Foo(20)
\\ for each arrayitem call Foo(20)
TestThis()
\\ call once foo(20) and result copy to each array item
Dim A(10)=Foo(20)
TestThis()
Bar=Lambda Foo (m)->{
->Foo(m)
}
\\ Not only the same id, but the same group
\\ each item is pointer to group
Dim A(10)=Bar(20)
TestThis()
Sub TestThis()
Local i
For i=0 to 9 {
For A(i){
.x++
Print .id , .x
}
}
Print
End Sub
}
Checkit

View file

@ -0,0 +1 @@
{x, x, x, x} /. x -> Random[]

View file

@ -0,0 +1 @@
{x, x, x, x} /. x :> Random[]

View file

@ -0,0 +1,9 @@
a: [1, 2]$
b: makelist(copy(a), 3);
[[1,2],[1,2],[1,2]]
b[1][2]: 1000$
b;
[[1,1000],[1,2],[1,2]]

View file

@ -0,0 +1 @@
VAR a: ARRAY[1..N] OF T

View file

@ -0,0 +1,56 @@
MODULE DistinctObjects EXPORTS Main;
IMPORT IO, Random;
VAR
random := NEW(Random.Default).init();
TYPE
T = RECORD (* value will initialize to 2 unless otherwise specified *)
value: INTEGER := 2;
END;
CONST Size = 3;
VAR
(* initialize records *)
t1 := T { 3 };
t2 := T { 4 };
t3 : T; (* t3's value will be default (2) *)
(* initialize a reference to T with value 100 *)
tr := NEW(REF T, value := 100);
(* initialize an array of records *)
a := ARRAY[1..Size] OF T { t1, t2, t3 };
(* initialize an array of integers *)
b := ARRAY[1..Size] OF INTEGER { -9, 2, 6 };
(* initialize an array of references to a record -- NOT copied! *)
c := ARRAY[1..Size] OF REF T { tr, tr, tr };
BEGIN
(* display the data *)
FOR i := 1 TO Size DO
IO.PutInt(a[i].value); IO.Put(" , ");
IO.PutInt(b[i]); IO.Put(" , ");
IO.PutInt(c[i].value); IO.Put(" ; ");
END;
IO.PutChar('\n');
(* re-initialize a's data to random integers *)
FOR i := 1 TO Size DO a[i].value := random.integer(-10, 10); END;
(* modify "one" element of c *)
c[1].value := 0;
(* display the data *)
FOR i := 1 TO Size DO
IO.PutInt(a[i].value); IO.Put(" , ");
IO.PutInt(b[i]); IO.Put(" , ");
IO.PutInt(c[i].value); IO.Put(" ; ");
END;
IO.PutChar('\n');
END DistinctObjects.

View file

@ -0,0 +1 @@
{ [foo()] * n }

View file

@ -0,0 +1 @@
{ foo * n }

View file

@ -0,0 +1,30 @@
import sequtils, strutils
# Creating a sequence containing sequences of integers.
var s1 = newSeq[seq[int]](5)
for item in s1.mitems: item = @[1]
echo "s1 = ", s1 # @[@[1], @[1], @[1], @[1], @[1]]
s1[0].add 2
echo "s1 = ", s1 # @[@[1, 2], @[1], @[1], @[1], @[1]]
# Using newSeqWith.
var s2 = newSeqWith(5, @[1])
echo "s2 = ", s2 # @[@[1], @[1], @[1], @[1], @[1]]
s2[0].add 2
echo "s2 = ", s2 # @[@[1, 2], @[1], @[1], @[1], @[1]]
# Creating a sequence containing pointers.
proc newInt(n: int): ref int =
new(result)
result[] = n
var s3 = newSeqWith(5, newInt(1))
echo "s3 contains references to ", s3.mapIt(it[]).join(", ") # 1, 1, 1, 1, 1
s3[0][] = 2
echo "s3 contains references to ", s3.mapIt(it[]).join(", ") # 2, 1, 1, 1, 1
# How to create non distinct elements.
let p = newInt(1)
var s4 = newSeqWith(5, p)
echo "s4 contains references to ", s4.mapIt(it[]).join(", ") # 1, 1, 1, 1, 1
s4[0][] = 2
echo "s4 contains references to ", s4.mapIt(it[]).join(", ") # 2, 2, 2, 2, 2

View file

@ -0,0 +1,3 @@
Array.make n (new foo);;
(* here (new foo) can be any expression that returns a new object,
record, array, or string *)

View file

@ -0,0 +1 @@
Array.init n (fun _ -> new foo);;

View file

@ -0,0 +1 @@
ListBuffer init(10, #[ Float rand ]) println

View file

@ -0,0 +1 @@
ListBuffer initValue(10, Float rand) println

View file

@ -0,0 +1,19 @@
-- get an array of directory objects
array = fillArrayWith(3, .directory)
say "each object will have a different identityHash"
say
loop d over array
say d d~identityHash
end
::routine fillArrayWith
use arg size, class
array = .array~new(size)
loop i = 1 to size
-- Note, this assumes this object class can be created with
-- no arguments
array[i] = class~new
end
return array

View file

@ -0,0 +1,5 @@
declare
Xs = {MakeList 5} %% a list of 5 unbound variables
in
{ForAll Xs OS.rand} %% fill it with random numbers (CORRECT)
{Show Xs}

View file

@ -0,0 +1,7 @@
declare
Arr = {Array.new 0 10 {OS.rand}} %% WRONG: contains ten times the same number
in
%% CORRECT: fill it with ten (probably) different numbers
for I in {Array.low Arr}..{Array.high Arr} do
Arr.I := {OS.rand}
end

View file

@ -0,0 +1,3 @@
(Foo->new) x $n
# here Foo->new can be any expression that returns a reference representing
# a new object

View file

@ -0,0 +1 @@
map { Foo->new } 1 .. $n;

View file

@ -0,0 +1,8 @@
(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"x"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[$]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">5</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">'y'</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<span style="color: #000080;font-style:italic;">-- s[2] = s ?s</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<!--

View file

@ -0,0 +1,3 @@
(phixonline)-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">my_func</span><span style="color: #0000FF;">(),</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<!--

View file

@ -0,0 +1,6 @@
(phixonline)-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">my_func</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--

View file

@ -0,0 +1,2 @@
: (make (do 5 (link (new))))
-> ($384717187 $384717189 $384717191 $384717193 $384717195)

View file

@ -0,0 +1,6 @@
: (mapcar box (range 1 5))
-> ($384721107 $384721109 $384721111 $384721113 $384721115)
: (val (car @))
-> 1
: (val (cadr @@))
-> 2

View file

@ -0,0 +1,3 @@
1..3 | ForEach-Object {((Get-Date -Hour ($_ + (1..4 | Get-Random))).AddDays($_ + (1..4 | Get-Random)))} |
Select-Object -Unique |
ForEach-Object {$_.ToString()}

View file

@ -0,0 +1,3 @@
1..3 | ForEach-Object {((Get-Date -Hour ($_ + (1..4 | Get-Random))).AddDays($_ + (1..4 | Get-Random)))} |
Select-Object -Unique |
ForEach-Object {$_.ToString()}

View file

@ -0,0 +1,25 @@
n=Random(50)+25
Dim A.i(n)
; Creates a Array of n [25-75] elements depending on the outcome of Random().
; Each element will be initiated to zero.
For i=0 To ArraySize(A())
A(i)=2*i
Next i
; Set each individual element at a wanted (here 2*i) value and
; automatically adjust accordingly to the unknown length of the Array.
NewList *PointersToA()
For i=0 To ArraySize(A())
AddElement(*PointersToA())
*PointersToA()=@A(i)
Next
; Create a linked list of the same length as A() above.
; Each element is then set to point to the Array element
; of the same order.
ForEach *PointersToA()
Debug PeekI(*PointersToA())
Next
; Verify by sending each value of A() via *PointersToA()
; to the debugger's output.

View file

@ -0,0 +1 @@
[Foo()] * n # here Foo() can be any expression that returns a new object

View file

@ -0,0 +1 @@
[Foo() for i in range(n)]

View file

@ -0,0 +1 @@
rep(foo(), n) # foo() is any code returning a value

View file

@ -0,0 +1 @@
replicate(n, foo())

View file

@ -0,0 +1,17 @@
/*REXX program does a list comprehension that will create N random integers, all unique.*/
parse arg n lim . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 1000 /*Not specified? Then use the default.*/
if lim=='' | lim=="," then lim= 100000 /* " " " " " " */
lim= min(lim, 1e5) /*limit the random range if necessary. */
randoms= /*will contain random list of integers.*/
$= .
do j=1 for n /*gen a unique random integer for list.*/
do until wordpos($, randoms)==0 /*ensure " " " " " */
$= random(0, lim) /*Not unique? Then obtain another int.*/
end /*until*/ /*100K is the maximum range for RANDOM.*/
randoms= $ randoms /*add an unique random integer to list.*/
end /*j*/
say words(randoms) ' unique numbers generated.' /*stick a fork in it, we're all done. */

View file

@ -0,0 +1,7 @@
#lang racket
;; a list of 10 references to the same vector
(make-list 10 (make-vector 10 0))
;; a list of 10 distinct vectors
(build-list 10 (λ (n) (make-vector 10 0)))

View file

@ -0,0 +1 @@
my @a = Foo.new xx $n;

View file

@ -0,0 +1,2 @@
[Foo.new] * n # here Foo.new can be any expression that returns a new object
Array.new(n, Foo.new)

Some files were not shown because too many files have changed in this diff Show more