task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #PARI.2FGP | PARI/GP | procedure super;
var
f: boolean;
procedure nestedProcedure;
var
c: char;
begin
// here, `f`, `c`, `nestedProcedure` and `super` are available
end;
procedure commonTask;
var
f: boolean;
begin
// here, `super`, `commonTask` and _only_ the _local_ `f` is available
end;
var
c: char;
procedure fooBar;... |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #D | D |
import std.stdio;
void main() {
auto coconuts = 11;
outer:
foreach (ns; 2..10) {
int[] hidden = new int[ns];
coconuts = (coconuts / ns) * ns + 1;
while (true) {
auto nc = coconuts;
foreach (s; 1..ns+1) {
if (nc % ns == 1) {
... |
http://rosettacode.org/wiki/Secure_temporary_file | Secure temporary file | Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function shou... | #Rust | Rust | // 202100322 Rust programming solution
use tempfile::tempfile;
fn main() {
let fh = tempfile();
println!("{:?}", fh);
} |
http://rosettacode.org/wiki/Secure_temporary_file | Secure temporary file | Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function shou... | #Scala | Scala | import java.io.{File, FileWriter, IOException}
def writeStringToFile(file: File, data: String, appending: Boolean = false) =
using(new FileWriter(file, appending))(_.write(data))
def using[A <: {def close() : Unit}, B](resource: A)(f: A => B): B =
try f(resource) finally resource.close()
try {
v... |
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #Objeck | Objeck | no warnings 'redefine';
sub logger { print shift . ": Dicitur clamantis in deserto." }; # discarded
logger('A'); # can use before defined
HighLander::logger('B'); # ditto, but referring to another package
package HighL... |
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #Oforth | Oforth | no warnings 'redefine';
sub logger { print shift . ": Dicitur clamantis in deserto." }; # discarded
logger('A'); # can use before defined
HighLander::logger('B'); # ditto, but referring to another package
package HighL... |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #Arturo | Arturo | define :city [name population][]
records: map [
["Lagos" 21.0]
["Cairo" 15.2]
["Kinshasa-Brazzaville" 11.3]
["Greater Johannesburg" 7.55]
["Mogadishu" 5.85]
["Khartoum-Omdurman" 4.98]
["Dar Es Salaam" 4.7]
["Alexandria" 4.58]
["Abidjan" 4.4]
["Casablanca" 3.98]
] => [to :city]
... |
http://rosettacode.org/wiki/Same_fringe | Same fringe | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many compu... | #Bracmat | Bracmat | ( ( T
=
. ( next
= node stack rhs
. !arg:%?node ?stack
& whl
' ( !node:(?node.?rhs)
& !rhs !stack:?stack
)
& (!node.!stack)
)
& !arg:(?stackA,?stackB)
& whl
' ( !stackA:~
& !s... |
http://rosettacode.org/wiki/Same_fringe | Same fringe | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many compu... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <ucontext.h>
typedef struct {
ucontext_t caller, callee;
char stack[8192];
void *in, *out;
} co_t;
co_t * co_new(void(*f)(), void *data)
{
co_t * c = malloc(sizeof(*c));
getcontext(&c->callee);
c->in = data;
c->callee.uc_stack.ss_sp = c->stack;
c->callee.uc_... |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #M2000_Interpreter | M2000 Interpreter |
Module EratosthenesSieve (x) {
\\ Κόσκινο του Ερατοσθένη
If x>200000 Then Exit
Dim i(x+1)
k=2
k2=sqrt(x)
While k<=k2 {
m=k+k
While m<=x {
i(m)=1
m+=k
}
{k++:if i(k) then loop
}
}
... |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #Pascal | Pascal | procedure super;
var
f: boolean;
procedure nestedProcedure;
var
c: char;
begin
// here, `f`, `c`, `nestedProcedure` and `super` are available
end;
procedure commonTask;
var
f: boolean;
begin
// here, `super`, `commonTask` and _only_ the _local_ `f` is available
end;
var
c: char;
procedure fooBar;... |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #Perl | Perl | 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. |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #Elixir | Elixir | defmodule RC do
def valid?(sailor, nuts), do: valid?(sailor, nuts, sailor)
def valid?(sailor, nuts, 0), do: nuts > 0 and rem(nuts,sailor) == 0
def valid?(sailor, nuts, _) when rem(nuts,sailor)!=1, do: false
def valid?(sailor, nuts, i) do
valid?(sailor, nuts - div(nuts,sailor) - 1, i-1)
end
end
Enum.ea... |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #Forth | Forth | : total
over * over 1- rot 0 ?do
over over mod if dup xor swap leave else over over / 1+ rot + swap then
loop drop
;
: sailors
1+ 2 ?do
1 begin i over total dup 0= while drop 1+ repeat cr i 0 .r ." : " . .
loop
;
9 sailors |
http://rosettacode.org/wiki/Secure_temporary_file | Secure temporary file | Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function shou... | #Sidef | Sidef | var tmpfile = require('File::Temp');
var fh = tmpfile.new(UNLINK => 0);
say fh.filename;
fh.print("Hello, World!\n");
fh.close; |
http://rosettacode.org/wiki/Secure_temporary_file | Secure temporary file | Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function shou... | #Standard_ML | Standard ML | val filename = OS.FileSys.tmpName (); |
http://rosettacode.org/wiki/Secure_temporary_file | Secure temporary file | Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function shou... | #Tcl | Tcl | set chan [file tempfile filenameVar] |
http://rosettacode.org/wiki/Secure_temporary_file | Secure temporary file | Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function shou... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
tmpfile="test.txt"
ERROR/STOP CREATE (tmpfile,seq-E,-std-)
text="hello world"
FILE $tmpfile = text
- tmpfile "test.txt" can only be accessed by one user an will be deleted upon programm termination
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #Perl | Perl | no warnings 'redefine';
sub logger { print shift . ": Dicitur clamantis in deserto." }; # discarded
logger('A'); # can use before defined
HighLander::logger('B'); # ditto, but referring to another package
package HighL... |
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #Phix | Phix |
Functions are normally internal to a program. If they are at the nesting level
immediately within the program, they are accessible from anywhere in the program.
Functions can also be encapsuled in a package, and the function name exported.
Functions can be compiled separately, and then linked with a program
in wh... |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #BASIC | BASIC | 100 nc=0
110 read n$
120 if n$="" then 160
130 read p$
140 nc=nc+1
150 goto 110
160 restore
170 dim ci$(nc-1,1)
180 for i=0 to nc-1
190 : for j=0 to 1
200 : read ci$(i,j)
210 : next j
220 next i
230 :
240 print chr$(14);:rem text mode
250 print: print "Test 1. name='Dar Es Salaam':"
260 rem search uses query function ... |
http://rosettacode.org/wiki/Same_fringe | Same fringe | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many compu... | #C.23 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Same_Fringe
{
class Program
{
static void Main()
{
var rnd = new Random(110456);
var randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();
var bt1 = new BinTree<int>(randList);
// Shuffling will create ... |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #M4 | M4 | define(`lim',100)dnl
define(`for',
`ifelse($#,0,
``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')dnl
for(`j',2,lim,1,
`ifdef(a[j],
`',
`j for(`k',eval(j*j),lim,j,
`define(a[k],1)')')')
|
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #Phix | Phix | forward function localf() -- not normally necesssary, but will not harm
forward global function globalf() -- ""
function localf()
return 1
end function
global function globalf()
return 2
end function
|
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #PicoLisp | PicoLisp | $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
} |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #FreeBASIC | FreeBASIC |
Dim As Integer cocos = 11
For ns As Integer = 2 To 9
Dim As Integer oculta(ns)
cocos = Int(cocos / ns) * ns + 1
Do
Dim As Integer nc = cocos
For s As Integer = 1 To ns+1
If nc Mod ns = 1 Then
oculta(s-1) = Int(nc / ns)
nc = nc - (oculta(s-1) + ... |
http://rosettacode.org/wiki/Secure_temporary_file | Secure temporary file | Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function shou... | #UNIX_Shell | UNIX Shell | RESTOREUMASK=$(umask)
TRY=0
while :; do
TRY=$(( TRY + 1 ))
umask 0077
MYTMP=${TMPDIR:-/tmp}/$(basename $0).$$.$(date +%s).$TRY
trap "rm -fr $MYTMP" EXIT
mkdir "$MYTMP" 2>/dev/null && break
done
umask "$RESTOREUMASK"
cd "$MYTMP" || {
echo "Temporary directory failure on $MYTMP" >&2
exit 1; } |
http://rosettacode.org/wiki/Secure_temporary_file | Secure temporary file | Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function shou... | #Wren | Wren | import "random" for Random
import "/ioutil" for File, FileUtil
import "/fmt" for Fmt
var rand = Random.new()
var createTempFile = Fn.new { |lines|
var tmp
while (true) {
// create a name which includes a random 6 digit number
tmp = "/tmp/temp%(Fmt.swrite("$06d", rand.int(1e6))).tmp"
... |
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #PL.2FI | PL/I |
Functions are normally internal to a program. If they are at the nesting level
immediately within the program, they are accessible from anywhere in the program.
Functions can also be encapsuled in a package, and the function name exported.
Functions can be compiled separately, and then linked with a program
in wh... |
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #PowerShell | PowerShell |
function global:Get-DependentService
{
Get-Service | Where-Object {$_.DependentServices}
}
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #Python | Python |
(define (foo x)
(define (bar y) (+ x y))
(bar 2))
(foo 1) ; => 3
(bar 1) ; => error
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #Racket | Racket |
(define (foo x)
(define (bar y) (+ x y))
(bar 2))
(foo 1) ; => 3
(bar 1) ; => error
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #Raku | Raku | CALLER # Contextual symbols in the immediate caller's lexical scope
OUTER # Symbols in the next outer lexical scope
UNIT # Symbols in the outermost lexical scope of compilation unit
SETTING # Lexical symbols in the unit's DSL (usually CORE)
PARENT # Symbols in this package's parent package (or lexical ... |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #C | C |
#include <stdint.h> /* intptr_t */
#include <stdio.h>
#include <stdlib.h> /* bsearch */
#include <string.h>
#include <search.h> /* lfind */
#define LEN(x) (sizeof(x) / sizeof(x[0]))
struct cd {
char *name;
double population;
};
/* Return -1 if name could not be found */
int search_get_index_by_name(cons... |
http://rosettacode.org/wiki/Same_fringe | Same fringe | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many compu... | #C.2B.2B | C++ | #include <algorithm>
#include <coroutine>
#include <iostream>
#include <memory>
#include <tuple>
#include <variant>
using namespace std;
class BinaryTree
{
// C++ does not have a built in tree type. The binary tree is a recursive
// data type that is represented by an empty tree or a node the has a value
// ... |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #MAD | MAD | NORMAL MODE IS INTEGER
R TO GENERATE MORE PRIMES, CHANGE BOTH THESE NUMBERS
BOOLEAN PRIME
DIMENSION PRIME(10000)
MAXVAL = 10000
PRINT FORMAT BEGIN,MAXVAL
R ASSUME ALL ARE PRIMES AT BEGINNING
THROUGH SET, FOR I=2, 1... |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #PowerShell | PowerShell | $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
} |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #PureBasic | PureBasic | ;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 sim... |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #Go | Go | package main
import "fmt"
func main() {
coconuts := 11
outer:
for ns := 2; ns < 10; ns++ {
hidden := make([]int, ns)
coconuts = (coconuts/ns)*ns + 1
for {
nc := coconuts
for s := 1; s <= ns; s++ {
if nc%ns == 1 {
hidden[s-1]... |
http://rosettacode.org/wiki/Secure_temporary_file | Secure temporary file | Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function shou... | #zkl | zkl | zkl: File.mktmp()
File(zklTmpFile082p1V)
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #REXX | REXX | /*REXX program demonstrates the use of labels and also a CALL statement. */
blarney = -0 /*just a blarney & balderdash statement*/
signal do_add /*transfer program control to a label.*/
ttt = sinD(30) ... |
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #Ring | Ring |
# Project : Scope/Function names and labels
see "What is your name?" + nl
give name
welcome(name)
func welcome(name)
see "hello " + name + nl
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #Ruby | Ruby |
def welcome(name)
puts "hello #{name}"
end
puts "What is your name?"
$name = STDIN.gets
welcome($name)
return |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #C.23 | C# | using System;
using System.Collections.Generic;
namespace RosettaSearchListofRecords
{
class Program
{
static void Main(string[] args)
{
var dataset = new List<Dictionary<string, object>>() {
new Dictionary<string, object> {{ "name" , "Lagos"}, {"po... |
http://rosettacode.org/wiki/Safe_addition | Safe addition | Implementation of interval arithmetic and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.
For example, for an addition, it is the operations +↑ and +↓ defined as: a +↓ b ≤ a + b ≤ a +↑ b.
Additionally it is desired that the widt... | #Ada | Ada | type Interval is record
Lower : Float;
Upper : Float;
end record; |
http://rosettacode.org/wiki/Same_fringe | Same fringe | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many compu... | #Clojure | Clojure | (defn fringe-seq [branch? children content tree]
(letfn [(walk [node]
(lazy-seq
(if (branch? node)
(if (empty? (children node))
(list (content node))
(mapcat walk (children node)))
(list node))))]
(walk tree))) |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #Maple | Maple | Eratosthenes := proc(n::posint)
local numbers_to_check, i, k;
numbers_to_check := [seq(2 .. n)];
for i from 2 to floor(sqrt(n)) do
for k from i by i while k <= n do
if evalb(k <> i) then
numbers_to_check[k - 1] := 0;
end if;
end do;
end do;
numbers_to_check... |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #Python | Python | >>> 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
prin... |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #R | R | X <- "global x"
f <- function() {
x <- "local x"
print(x) #"local x"
}
f() #prints "local x"
print(x) #prints "global x" |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #Haskell | Haskell | import Control.Monad ((>=>))
import Data.Maybe (mapMaybe)
import System.Environment (getArgs)
-- Takes the number of sailors and the final number of coconuts. Returns
-- Just the associated initial number of coconuts and Nothing otherwise.
tryFor :: Int -> Int -> Maybe Int
tryFor s = foldr (>=>) pure $ replicate s st... |
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #Scala | Scala | object ScopeFunction extends App {
val c = new C()
val d = new D()
val n = 1
def a() = println("calling a")
trait E {
def m() = println("calling m")
}
a() // OK as a is internal
B.f() // OK as f is public
class C {
// class level function visible everywhere, by default
def g() = pr... |
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #Sidef | Sidef | # Nested functions
func outer {
func inner {}; # not visible outside
}
# Nested classes
class Outer {
class Inner {}; # not visisble outside
} |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #C.2B.2B | C++ | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
struct city {
std::string name;
float population;
};
int main()
{
std::vector<city> cities = {
{ "Lagos", 21 },
{ "Cairo", 15.2 },
{ "Kinshasa-Brazzaville", 11.3 },
{ "Greater Johannesburg", 7.55... |
http://rosettacode.org/wiki/Safe_addition | Safe addition | Implementation of interval arithmetic and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.
For example, for an addition, it is the operations +↑ and +↓ defined as: a +↓ b ≤ a + b ≤ a +↑ b.
Additionally it is desired that the widt... | #AutoHotkey | AutoHotkey | Msgbox % IntervalAdd(1,2) ; [2.999999,3.000001]
SetFormat, FloatFast, 0.20
Msgbox % IntervalAdd(1,2) ; [2.99999999999999910000,3.00000000000000090000]
;In v1.0.48+, floating point variables have about 15 digits of precision internally
;unless SetFormat Float (i.e. the slow mode) is present anywhere in the script. ... |
http://rosettacode.org/wiki/Safe_addition | Safe addition | Implementation of interval arithmetic and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.
For example, for an addition, it is the operations +↑ and +↓ defined as: a +↓ b ≤ a + b ≤ a +↑ b.
Additionally it is desired that the widt... | #C | C | #include <fenv.h> /* fegetround(), fesetround() */
#include <stdio.h> /* printf() */
/*
* Calculates an interval for a + b.
* interval[0] <= a + b
* a + b <= interval[1]
*/
void
safe_add(volatile double interval[2], volatile double a, volatile double b)
{
#pragma STDC FENV_ACCESS ON
unsigned int orig;
ori... |
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes | Safe primes and unsafe primes | Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
... | #ALGOL_68 | ALGOL 68 | # find and count safe and unsafe primes #
# safe primes are primes p such that ( p - 1 ) / 2 is also prime #
# unsafe primes are primes that are not safe #
PR heap=128M PR # set heap memory size for Algol 68G #
... |
http://rosettacode.org/wiki/Same_fringe | Same fringe | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many compu... | #D | D | struct Node(T) {
T data;
Node* L, R;
}
bool sameFringe(T)(Node!T* t1, Node!T* t2) {
T[] scan(Node!T* t) {
if (!t) return [];
return (!t.L && !t.R) ? [t.data] : scan(t.L) ~ scan(t.R);
}
return scan(t1) == scan(t2);
}
void main() {
import std.stdio;
alias N = Node!int;
... |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Eratosthenes[n_] := Module[{numbers = Range[n]},
Do[If[numbers[[i]] != 0, Do[numbers[[i j]] = 0, {j, 2, n/i}]], {i,
2, Sqrt[n]}];
Select[numbers, # > 1 &]]
Eratosthenes[100] |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #Racket | Racket | my $lexical-variable;
our $package-variable;
state $persistent-lexical;
has $.public-attribute; |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #Raku | Raku | my $lexical-variable;
our $package-variable;
state $persistent-lexical;
has $.public-attribute; |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #J | J | I.(=<.)%&5 verb def'4*(y-1)%5'^:5 i.10000
3121 |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #Java | Java | public class Test {
static boolean valid(int n, int nuts) {
for (int k = n; k != 0; k--, nuts -= 1 + nuts / n)
if (nuts % n != 1)
return false;
return nuts != 0 && (nuts % n == 0);
}
public static void main(String[] args) {
int x = 0;
for (int ... |
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #Tcl | Tcl | doFoo 1 2 3; # Will produce an error
proc doFoo {a b c} {
puts [expr {$a + $b*$c}]
}
doFoo 1 2 3; # Will now print 7 (and will continue to do so until doFoo is renamed or deleted |
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #UNIX_Shell | UNIX Shell | #!/bin/sh
multiply 3 4 # This will not work
echo $? # A bogus value was returned because multiply definition has not yet been run.
multiply() {
return `expr $1 \* $2` # The backslash is required to suppress interpolation
}
multiply 3 4 # Ok. It works now.
echo $? # This gives 12 |
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #Wren | Wren | //func.call() /* invalid, can't call func before its declared */
var func = Fn.new { System.print("func has been called.") }
func.call() // fine
//C.init() /* not OK, as C is null at this point */
class C {
static init() { method() } // fine even though 'method' not yet declared
static method() { Syst... |
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #XPL0 | XPL0 | class C{ fcn [private] f{} } |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #Clojure | Clojure | (def records [{:idx 8, :name "Abidjan", :population 4.4}
{:idx 7, :name "Alexandria", :population 4.58}
{:idx 1, :name "Cairo", :population 15.2}
{:idx 9, :name "Casablanca", :population 3.98}
{:idx 6, :name "Dar ... |
http://rosettacode.org/wiki/Safe_addition | Safe addition | Implementation of interval arithmetic and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.
For example, for an addition, it is the operations +↑ and +↓ defined as: a +↓ b ≤ a + b ≤ a +↑ b.
Additionally it is desired that the widt... | #C.23 | C# | using System;
namespace SafeAddition {
class Program {
static float NextUp(float d) {
if (d == 0.0) return float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
i... |
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes | Safe primes and unsafe primes | Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
... | #AppleScript | AppleScript | -- Heavy-duty Sieve of Eratosthenes handler.
-- Returns a list containing either just the primes up to a given limit ('crossingsOut' = false) or, as in this task,
-- both the primes and 'missing values' representing the "crossed out" non-primes ('crossingsOut' = true).
on sieveForPrimes given limit:limit, crossingsOut:... |
http://rosettacode.org/wiki/Same_fringe | Same fringe | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many compu... | #Go | Go | package main
import "fmt"
type node struct {
int
left, right *node
}
// function returns a channel that yields the leaves of the tree.
// the channel is closed after all leaves are received.
func leaves(t *node) chan int {
ch := make(chan int)
// recursive function to walk tree.
var f func(*no... |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #MATLAB_.2F_Octave | MATLAB / Octave | function P = erato(x) % Sieve of Eratosthenes: returns all primes between 2 and x
P = [0 2:x]; % Create vector with all ints between 2 and x where
% position 1 is hard-coded as 0 since 1 is not a prime.
for n = 2:sqrt(x) % All primes factors lie betwe... |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #REXX | REXX | /*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 t... |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #Ruby | Ruby | class Demo
#public methods here
protected
#protect methods here
private
#private methods
end |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #Scala | Scala | 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
name... |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #JavaScript | JavaScript | (function () {
// wakeSplit :: Int -> Int -> Int -> Int
function wakeSplit(intNuts, intSailors, intDepth) {
var nDepth = intDepth !== undefined ? intDepth : intSailors,
portion = Math.floor(intNuts / intSailors),
remain = intNuts % intSailors;
return 0 >= portion || r... |
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #zkl | zkl | class C{ fcn [private] f{} } |
http://rosettacode.org/wiki/Scope/Function_names_and_labels | Scope/Function names and labels | Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 9000 REM The function is immediately visible and usable
9010 DEF FN s(x)=x*x
PRINT FN s(5): REM This will work immediately
GO TO 50: REM This will work immediately |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #Common_Lisp | Common Lisp | (defstruct city
(name nil :type string)
(population nil :type number))
(defparameter *cities*
(list (make-city :name "Lagos" :population 21.0)
(make-city :name "Cairo" :population 15.2)
(make-city :name "Kinshasa-Brazzaville" :population 11.3)
(make-city :na... |
http://rosettacode.org/wiki/Safe_addition | Safe addition | Implementation of interval arithmetic and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.
For example, for an addition, it is the operations +↑ and +↓ defined as: a +↓ b ≤ a + b ≤ a +↑ b.
Additionally it is desired that the widt... | #C.2B.2B | C++ | #include <iostream>
#include <tuple>
union conv {
int i;
float f;
};
float nextUp(float d) {
if (isnan(d) || d == -INFINITY || d == INFINITY) return d;
if (d == 0.0) return FLT_EPSILON;
conv c;
c.f = d;
c.i++;
return c.f;
}
float nextDown(float d) {
if (isnan(d) || d == -IN... |
http://rosettacode.org/wiki/Safe_addition | Safe addition | Implementation of interval arithmetic and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.
For example, for an addition, it is the operations +↑ and +↓ defined as: a +↓ b ≤ a + b ≤ a +↑ b.
Additionally it is desired that the widt... | #D | D | import std.traits;
auto safeAdd(T)(T a, T b)
if (isFloatingPoint!T) {
import std.math; // nexDown, nextUp
import std.typecons; // tuple
return tuple!("d", "u")(nextDown(a+b), nextUp(a+b));
}
import std.stdio;
void main() {
auto a = 1.2;
auto b = 0.03;
auto r = safeAdd(a, b);
writefln... |
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes | Safe primes and unsafe primes | Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
... | #AWK | AWK |
# syntax: GAWK -f SAFE_PRIMES_AND_UNSAFE_PRIMES.AWK
BEGIN {
for (i=1; i<1E7; i++) {
if (is_prime(i)) {
arr[i] = ""
}
}
# safe:
stop1 = 35 ; stop2 = 1E6 ; stop3 = 1E7
count1 = count2 = count3 = 0
printf("The first %d safe primes:",stop1)
for (i=3; count1<stop1; i+=2) {
... |
http://rosettacode.org/wiki/Same_fringe | Same fringe | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many compu... | #Haskell | Haskell | data Tree a
= Leaf a
| Node (Tree a)
(Tree a)
deriving (Show, Eq)
fringe :: Tree a -> [a]
fringe (Leaf x) = [x]
fringe (Node n1 n2) = fringe n1 ++ fringe n2
sameFringe
:: (Eq a)
=> Tree a -> Tree a -> Bool
sameFringe t1 t2 = fringe t1 == fringe t2
main :: IO ()
main = do
let a = Node (Leaf 1)... |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #Maxima | Maxima | sieve(n):=block(
[a:makelist(true,n),i:1,j],
a[1]:false,
do (
i:i+1,
unless a[i] do i:i+1,
if i*i>n then return(sublist_indices(a,identity)),
for j from i*i step i while j<=n do a[j]:false
)
)$ |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #Tcl | Tcl | 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
name... |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #TI-89_BASIC | TI-89 BASIC | Local x
2 → x
Return x^x |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #TXR | TXR | @(maybe)@# perhaps this subclause suceeds or not
@ (block foo)
@ (bind a "a")
@ (accept foo)
@(end)
@(bind b "b") |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #jq | jq | def until(cond; next): def _until: if cond then . else (next|_until) end; _until; |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #Julia | Julia |
function validnutsforsailors(sailors, finalpile)
for i in sailors:-1:1
if finalpile % sailors != 1
return false
end
finalpile -= Int(floor(finalpile/sailors) + 1)
end
(finalpile != 0) && (finalpile % sailors == 0)
end
function runsim()
println("Sailors Startin... |
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #EchoLisp | EchoLisp |
(require 'struct)
(require 'json)
;; importing data
(define cities
#<<
[{"name":"Lagos", "population":21}, {"name":"Cairo", "population":15.2}, {"name":"Kinshasa-Brazzaville", "population":11.3}, {"name":"Greater Johannesburg", "population":7.55}, {"name":"Mogadishu", "population":5.85}, {"name":"Khartoum-Omdurman"... |
http://rosettacode.org/wiki/Safe_addition | Safe addition | Implementation of interval arithmetic and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.
For example, for an addition, it is the operations +↑ and +↓ defined as: a +↓ b ≤ a + b ≤ a +↑ b.
Additionally it is desired that the widt... | #E | E | def makeInterval(a :float64, b :float64) {
require(a <= b)
def interval {
to least() { return a }
to greatest() { return b }
to __printOn(out) {
out.print("[", a, ", ", b, "]")
}
to add(other) {
require(a <=> b)
require(other.least() <=... |
http://rosettacode.org/wiki/Safe_addition | Safe addition | Implementation of interval arithmetic and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.
For example, for an addition, it is the operations +↑ and +↓ defined as: a +↓ b ≤ a + b ≤ a +↑ b.
Additionally it is desired that the widt... | #Forth | Forth | c-library m
s" m" add-lib
\c #include <math.h>
c-function fnextafter nextafter r r -- r
end-c-library
s" MAX-FLOAT" environment? drop fconstant MAX-FLOAT
: fstepdown ( F: r1 -- r2 )
MAX-FLOAT fnegate fnextafter ;
: fstepup ( F: r1 -- r2 )
MAX-FLOAT fnextafter ;
: savef+ ( F: r1 r2 -- r3 r4 ) \ r4 <= r1+r2 <... |
http://rosettacode.org/wiki/Safe_addition | Safe addition | Implementation of interval arithmetic and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.
For example, for an addition, it is the operations +↑ and +↓ defined as: a +↓ b ≤ a + b ≤ a +↑ b.
Additionally it is desired that the widt... | #Go | Go | package main
import (
"fmt"
"math"
)
// type requested by task
type interval struct {
lower, upper float64
}
// a constructor
func stepAway(x float64) interval {
return interval {
math.Nextafter(x, math.Inf(-1)),
math.Nextafter(x, math.Inf(1))}
}
// function requested by task
fun... |
http://rosettacode.org/wiki/Search_a_list | Search a list | Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in ... | #11l | 11l | V haystack = [‘Zig’, ‘Zag’, ‘Wally’, ‘Ronald’, ‘Bush’, ‘Krusty’, ‘Charlie’, ‘Bush’, ‘Bozo’]
L(needle) (‘Washington’, ‘Bush’)
X.try
print(haystack.index(needle)‘ ’needle)
X.catch ValueError
print(needle‘ is not in haystack’) |
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes | Safe primes and unsafe primes | Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
... | #BASIC256 | BASIC256 | arraybase 1
max = 1000000
sc1 = 0: usc1 = 0: sc2 = 0: usc2 = 0
safeprimes$ =""
unsafeprimes$ = ""
redim criba(max)
# False = prime, True = no prime
criba[0] = True
criba[1] = True
for i = 4 to max step 2
criba[i] = 1
next i
for i = 3 to sqr(max) +1 step 2
if criba[i] = False then
for j = i * i to max step i... |
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes | Safe primes and unsafe primes | Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
... | #C | C | #include <stdbool.h>
#include <stdio.h>
int primes[] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
211, 223, 227, 229, 233, 239, 241, 251, 257, 263... |
http://rosettacode.org/wiki/Same_fringe | Same fringe | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many compu... | #Icon_and_Unicon | Icon and Unicon | procedure main()
aTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]]
bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]]
write("aTree and bTree ",(sameFringe(aTree,bTree),"have")|"don't have",
" the same leaves.")
cTree := [1, [2, [4, [7]], [5]], [3, [6, [8]]]]
dTree := [1, [2, [4, [7]],... |
http://rosettacode.org/wiki/Sieve_of_Eratosthenes | Sieve of Eratosthenes | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed... | #MAXScript | MAXScript | fn eratosthenes n =
(
multiples = #()
print 2
for i in 3 to n do
(
if (findItem multiples i) == 0 then
(
print i
for j in (i * i) to n by i do
(
append multiples j
)
)
)
)
eratosthenes 100
|
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #Ursala | Ursala | local_shop = 0
hidden_variable = 3
#library+
this_public_constant = local_shop
a_visible_function = +
#library-
for_local_people = 7 |
http://rosettacode.org/wiki/Scope_modifiers | Scope modifiers | Most programming languages offer support for 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").
T... | #Wren | Wren | class MyClass {
construct new(a) {
_a = a // creates an instance field _a automatically
}
a { _a } // allow public access to the field
}
var mc = MyClass.new(3)
System.print(mc.a) // fine
System.print(mc._a) // can't access _a directly as its private to the class |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #Kotlin | Kotlin | // version 1.1.2
fun main(args: Array<String>) {
var coconuts = 11
outer@ for (ns in 2..9) {
val hidden = IntArray(ns)
coconuts = (coconuts / ns) * ns + 1
while (true) {
var nc = coconuts
for (s in 1..ns) {
if (nc % ns == 1) {
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.