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/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Euphoria | Euphoria | include EuWinGUI.ew
Window("EuWinGUI - Simple windowed application",100,100,360,100)
constant Button1 = Control(Button,"Click me",250,20,80,25)
constant Label1 = Control(Label,"There have been no clicks yet",10,25,200,18)
integer clicks
clicks = 0
-- Event loop
while 1 do
WaitEvent()
if EventOwner = Button1 and Event = Click then
clicks += 1
SetText(Label1,sprintf("You clicked me %d times",clicks))
end if
end while
CloseApp(0) |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #PicoLisp | PicoLisp | (mapc println '(a "cde" (X Y Z) 999)) |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #PL.2FI | PL/I | *process source attributes xref or(!);
/*********************************************************************
* 25.10.2013 Walter Pachl
* 'set dd:in=d:\sll.txt,recsize(80)'
* 'sll'
*********************************************************************/
sll: Proc Options(main);
Dcl in Record Input;
Dcl sysprint Print;
Dcl 1 elem Based(p),
2 next Ptr Init(null()),
2 value Char(20) Var;
Dcl head Ptr;
Dcl p Ptr;
Dcl prev Ptr;
Dcl i Bin Fixed(31);
Dcl rec Char(80) Var;
Dcl null Builtin;
On Endfile(in) goto show;
Do i=1 By 1;
Read File(in) Into(rec);
alloc elem set(p);
If i=1 Then Do;
head=p;
prev=head;
value=rec;
End;
Else Do;
prev->next=p;
prev=p;
value=rec;
End;
End;
show:
p=head;
Do i=1 By 1 while(p^=null());
Put Edit(i,p->value)(skip,f(3),x(1),a);
p=p->next;
End;
End; |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #REXX | REXX | /*REXX program demonstrates how to create and show a single-linked list.*/
@.=0 /*define a null linked list. */
call set@ 3 /*linked list: 12 Proth primes. */
call set@ 5
call set@ 13
call set@ 17
call set@ 41
call set@ 97
call set@ 113
call set@ 193
call set@ 241
call set@ 257
call set@ 353
call set@ 449
call list@
after = 97 /* ◄──── REXX code to do insert. */
newVal=100 /* ◄──── " " " " " */
#[email protected] /* ◄──── " " " " " */
call ins@ #,newVal /* ◄──── " " " " " */
say
say 'a new value of' newval "has been inserted after element value:" after
call list@
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────INS@ subroutine─────────────────────*/
ins@: procedure expose @.; parse arg #,y
@._last=@._last+1 /*bump number of list elements. */
_=@._last
@._._value=y /*define new value list element. */
@._._next=@.#._next
@.#._next=_
@..y=_ /*set a locator pointer to self. */
@.max_width=max(@.max_width,length(y)) /*set maximum width of any value.*/
return /*return to invoker of this sub. */
/*──────────────────────────────────LIST@ subroutine────────────────────*/
list@: say; w=max(7, @.max_width ) /*use the max width of nums or 7.*/
say center('item',6) center('value',w) center('next',6)
say center('' ,6,'─') center('' ,w,'─') center('' ,6,'─')
p=1
do j=1 until p==0 /*show all entries of linked list*/
say right(j,6) right(@.p._value,w) right(@.p._next,6)
[email protected]._next
end /*j*/
return
/*──────────────────────────────────SET@ subroutine─────────────────────*/
set@: procedure expose @.; parse arg y /*get element to be added to list*/
_=@._last /*set the previous last element. */
n=_+1 /*bump last ptr in linked list. */
@._._next=n /*set the next pointer value. */
@._last=n /*define next item in linked list*/
@.n._value=y /*set item to the value specified*/
@.n._next=0 /*set the next pointer value. */
@..y=n /*set a locator pointer to self. */
@.max_width=max(@.max_width,length(y)) /*set maximum width of any value.*/
return /*return to invoker of this sub. */ |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #IDL | IDL |
read,i,prompt='Input sleep time in seconds: '
print,'Sleeping...'
wait,i ; in seconds, but accepts floats(/fractional) as input
print,'Awake!'
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #J | J | sleep =: 6!:3
sleeping=: monad define
smoutput 'Sleeping...'
sleep y
smoutput 'Awake!'
) |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #zkl | zkl | fcn bubbleSort(list){
itemCount := list.len();
do{
hasChanged := False;
foreach index in (itemCount -= 1){
if (list[index] > list[index + 1]){
list.swap(index,index + 1);
hasChanged = True;
}
}
}while(hasChanged);
list
} |
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #11l | 11l | F sierpinski_square(fname, size, length, order)
V x = (size - length) / 2
V y = Float(length)
V angle = 0.0
V outfile = File(fname, ‘w’)
outfile.write(‘<svg xmlns='http://www.w3.org/2000/svg' width='’size‘' height='’size"'>\n")
outfile.write("<rect width='100%' height='100%' fill='white'/>\n")
outfile.write(‘<path stroke-width='1' stroke='black' fill='none' d='’)
V s = ‘F+XF+F+XF’
L 0 .< order
s = s.replace(‘X’, ‘XF-F+F-XF+F+XF-F+F-X’)
outfile.write(‘M’x‘,’y)
L(c) s
S c
‘F’
x += length * cos(radians(angle))
y += length * sin(radians(angle))
outfile.write(‘ L’x‘,’y)
‘+’
angle = (angle + 90) % 360
‘-’
angle = (angle - 90 + 360) % 360
outfile.write("'/>\n</svg>\n")
sierpinski_square(‘sierpinski_square.svg’, 635, 5, 5) |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #F.23 | F# | open System.Windows.Forms
let mutable clickCount = 0
let form = new Form()
let label = new Label(Text = "There have been no clicks yet.", Dock = DockStyle.Top)
form.Controls.Add(label)
let button = new Button(Text = "Click me", Dock = DockStyle.Bottom)
button.Click.Add(fun _ ->
clickCount <- clickCount+1
label.Text <- sprintf "Number of clicks: %i." clickCount)
form.Controls.Add(button)
Application.Run(form) |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #PureBasic | PureBasic | Procedure traverse(*node.MyData)
While *node
;access data, i.e. PrintN(Str(*node\Value))
*node = *node\next
Wend
EndProcedure
;called using
traverse(*firstnode.MyData) |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Python | Python | for node in lst:
print node.value |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Ruby | Ruby | class ListNode
def insert_after(search_value, new_value)
if search_value == value
self.succ = self.class.new(new_value, succ)
elsif self.succ.nil?
raise StandardError, "value #{search_value} not found in list"
else
self.succ.insert_after(search_value, new_value)
end
end
end
list = ListNode.new(:a, ListNode.new(:b))
list.insert_after(:a, :c) |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Rust | Rust | impl<T> List<T> {
pub fn new() -> Self {
List { head: None }
}
pub fn push(&mut self, elem: T) {
let new_node = Box::new(Node {
elem: elem,
next: self.head.take(),
});
self.head = Some(new_node);
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Java | Java |
import java.util.InputMismatchException;
import java.util.Scanner;
public class Sleep {
public static void main(final String[] args) throws InterruptedException {
try {
int ms = new Scanner(System.in).nextInt(); //Java's sleep method accepts milliseconds
System.out.println("Sleeping...");
Thread.sleep(ms);
System.out.println("Awake!");
} catch (InputMismatchException inputMismatchException) {
System.err.println("Exception: " + inputMismatchException);
}
}
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #JavaScript | JavaScript | <script>
setTimeout(function () {
document.write('Awake!')
}, prompt("Number of milliseconds to sleep"));
document.write('Sleeping... ');
</script> |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 5000 CLS
5002 LET a$="": FOR f=1 TO 64: LET a$=a$+CHR$ (32+INT (RND*96)): NEXT f
5004 PRINT a$; AT 10,0;"ZigZag BubbleSORT"
5010 LET la=LEN a$
5011 LET i=1: LET u=0
5020 LET d=0: LET p=(u=0)-(u=1)
5021 LET l=(i AND u=0)+(la-i+u AND u=1)
5030 IF u=0 THEN IF a$(l+1)>=a$(l) THEN GO TO 5050
5031 IF u=1 THEN IF a$(l-1)<=a$(l) THEN GO TO 5050
5040 LET d=1
5042 LET t$=a$(l+p)
5043 LET a$(l+p)=a$(l)
5044 LET a$(l)=t$
5050 LET l=l+p
5051 PRINT AT 10,21;a$(l);AT 12,0;a$
5055 IF l<=la-i AND l>=i THEN GO TO 5023
5061 LET i=i+NOT u
5063 LET u=NOT u
5064 IF d AND i<la THEN GO TO 5020
5072 PRINT AT 12,0;a$
9000 STOP |
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #C.2B.2B | C++ | // See https://en.wikipedia.org/wiki/Sierpi%C5%84ski_curve#Representation_as_Lindenmayer_system
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class sierpinski_square {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std::string& s);
double x_;
double y_;
int angle_;
int length_;
};
void sierpinski_square::write(std::ostream& out, int size, int length, int order) {
length_ = length;
x_ = (size - length)/2;
y_ = length;
angle_ = 0;
out << "<svg xmlns='http://www.w3.org/2000/svg' width='"
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "F+XF+F+XF";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s);
out << "'/>\n</svg>\n";
}
std::string sierpinski_square::rewrite(const std::string& s) {
std::string t;
for (char c : s) {
if (c == 'X')
t += "XF-F+F-XF+F+XF-F+F-X";
else
t += c;
}
return t;
}
void sierpinski_square::line(std::ostream& out) {
double theta = (3.14159265359 * angle_)/180.0;
x_ += length_ * std::cos(theta);
y_ += length_ * std::sin(theta);
out << " L" << x_ << ',' << y_;
}
void sierpinski_square::execute(std::ostream& out, const std::string& s) {
out << 'M' << x_ << ',' << y_;
for (char c : s) {
switch (c) {
case 'F':
line(out);
break;
case '+':
angle_ = (angle_ + 90) % 360;
break;
case '-':
angle_ = (angle_ - 90) % 360;
break;
}
}
}
int main() {
std::ofstream out("sierpinski_square.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return 1;
}
sierpinski_square s;
s.write(out, 635, 5, 5);
return 0;
} |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Factor | Factor | USING: accessors arrays kernel math math.parser namespaces
sequences ui ui.gadgets ui.gadgets.borders ui.gadgets.buttons
ui.gadgets.grids ui.gadgets.labels ui.gadgets.worlds ;
IN: rosetta-code.simple-windowed-application
SYMBOL: n
CONSTANT: on-btn-press [
parents second n get number>string <label> { 0 1 }
grid-add drop n inc
]
: build-ui ( -- ) [
f
T{ world-attributes { title "Simple windowed application" } }
clone
"click me" on-btn-press <border-button> 1array
"There have been no clicks yet" <label> 1array
2array <grid>
{ 100 100 } <border>
>>gadgets
open-window
] with-ui ;
: main ( -- ) 1 n set build-ui ;
MAIN: main |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Fantom | Fantom |
using fwt
using gfx
class SimpleApplication
{
public static Void main ()
{
Window
{
title = "Simple Window Application"
size = Size(350, 50)
clicked := 0
label := Label
{
text = "There have been no clicks yet"
}
Button
{
text = "Click me"
onAction.add |Event e|
{
clicked += 1
label.text = "There have been $clicked clicks"
}
},
label,
}.open
}
}
|
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Racket | Racket |
#lang racket
(define l (list 1 2 3))
;; scan the list and collect a list of function results
(map add1 l)
;; scan the list and run some function on each element for its side-effect
(for-each displayln l)
;; scan a list and sum up its elements
(foldl + 0 l)
;; same as the above three, using a more modern syntax that is often
;; more convenient
(for/list ([x (in-list l)]) (add1 x))
(for ([x (in-list l)]) (displayln x))
(for/fold ([sum 0]) ([x (in-list l)]) (+ x sum))
;; the same as the first, but make up a vector of results
(for/vector ([x (in-list l)]) (add1 x))
;; there is less support for mutable pairs, but it's still extensive
;; enough to cover all the basics
(require racket/mpair)
(define ml (mlist 1 2 3))
(mmap add1 ml)
(mfor-each displayln ml)
(for ([x (in-mlist ml)]) (displayln x))
|
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Raku | Raku | my $list = 1 => 2 => 3 => 4 => 5 => 6 => Mu;
loop (my $l = $list; $l; $l.=value) {
say $l.key;
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Scala | Scala |
/*
Here is a basic list definition
sealed trait List[+A]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]
*/
object List {
def add[A](as: List[A], a: A): List[A] = Cons(a, as)
}
|
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Scheme | Scheme | (define (insert-after a b lst)
(if (null? lst)
lst ; This should be an error, but we will just return the list untouched
(let ((c (car lst))
(cs (cdr lst)))
(if (equal? a c)
(cons a (cons b cs))
(cons c (insert-after a b cs)))))) |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Jsish | Jsish | /*
Sleep, in Jsish
*/
printf('Sleep time (in milliseconds)? ');
var ms = parseInt(console.input());
puts('Sleeping...');
sleep(ms);
puts('Awake!'); |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Julia | Julia |
print("Please enter sleep duration in seconds: ")
input = int(readline(STDIN))
println("Sleeping...")
sleep(input)
println("Awake!")
|
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #Factor | Factor | USING: accessors kernel L-system sequences ui ;
: square-curve ( L-system -- L-system )
L-parser-dialect >>commands
[ 90 >>angle ] >>turtle-values
"F+XF+F+XF" >>axiom
{
{ "X" "XF-F+F-XF+F+XF-F+F-X" }
} >>rules ;
[
<L-system> square-curve
"Sierpinski square curve" open-window
] with-ui |
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #Go | Go | package main
import (
"github.com/fogleman/gg"
"github.com/trubitsyn/go-lindenmayer"
"log"
"math"
)
const twoPi = 2 * math.Pi
var (
width = 770.0
height = 770.0
dc = gg.NewContext(int(width), int(height))
)
var cx, cy, h, theta float64
func main() {
dc.SetRGB(0, 0, 1) // blue background
dc.Clear()
cx, cy = 10, height/2+5
h = 6
sys := lindenmayer.Lsystem{
Variables: []rune{'X'},
Constants: []rune{'F', '+', '-'},
Axiom: "F+XF+F+XF",
Rules: []lindenmayer.Rule{
{"X", "XF-F+F-XF+F+XF-F+F-X"},
},
Angle: math.Pi / 2, // 90 degrees in radians
}
result := lindenmayer.Iterate(&sys, 5)
operations := map[rune]func(){
'F': func() {
newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)
dc.LineTo(newX, newY)
cx, cy = newX, newY
},
'+': func() {
theta = math.Mod(theta+sys.Angle, twoPi)
},
'-': func() {
theta = math.Mod(theta-sys.Angle, twoPi)
},
}
if err := lindenmayer.Process(result, operations); err != nil {
log.Fatal(err)
}
// needed to close the square at the extreme left
operations['+']()
operations['F']()
// create the image and save it
dc.SetRGB255(255, 255, 0) // yellow curve
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_square_curve.png")
} |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Forth | Forth | also minos
text-label ptr click-label
Variable click# click# off
: click-win ( -- ) screen self window new window with
X" There have been no clicks yet" text-label new
dup F bind click-label
^ S[ 1 click# +!
click# @ 0 <# #S s" Number of clicks: " holds #>
click-label assign ]S X" Click me" button new
&2 vabox new panel s" Clicks" assign show endwith ;
click-win |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #FreeBASIC | FreeBASIC |
#Include "windows.bi"
Dim As HWND Window_Main, Static_Text, Button_Click
Dim As MSG msg
Dim As Integer Num_Click
Dim As String Text
'Create a window with a static text control and a button:
Window_Main = CreateWindow("#32770", "Simple Windowed Application", WS_OVERLAPPEDWINDOW Or WS_VISIBLE, 100, 100, 350, 200, 0, 0, 0, 0)
Static_Text = CreateWindow("STATIC", "There have been no clicks yet", WS_VISIBLE Or WS_CHILD Or WS_BORDER, 10, 30, 300, 20, Window_Main, 0, 0, 0)
Button_Click = CreateWindow("BUTTON", "Click me", WS_VISIBLE Or WS_CHILD, 100, 70, 100, 20, Window_Main, 0, 0, 0)
'Windows message loop:
Num_Click = 0
While GetMessage(@msg, Window_Main, 0, 0)
TranslateMessage(@msg)
DispatchMessage(@msg)
Select Case msg.hwnd
Case Button_Click
If msg.message = WM_LBUTTONDOWN Then
Num_Click = Num_Click + 1
If Num_Click = 1 Then
Text = "Button has been clicked once"
Else
Text = "Button has been clicked " + Str(Num_Click) + " times"
End If
SetWindowText(Static_Text, Text)
End If
Case Window_Main
If msg.message = WM_COMMAND Then End
End Select
Wend
End
|
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Retro | Retro | : traverse ( l- ) repeat @ 0; again ; |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #REXX | REXX | /* REXX ********************************************************************
* 25.10.2013 Walter Pachl
*********************************************************************/
in='d:\sll.txt'
Do i=1 By 1 while lines(in)>0
rec=linein(in)
elem.i.val=rec
elem.i.next=0
ip=i-1
elem.ip.next=i
End;
c=1
Do While c<>0
Say c elem.c.val
c=elem.c.next
End |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Sidef | Sidef | func insert_after(a,b) {
b{:next} = a{:next};
a{:next} = b;
}
var B = Hash.new(
data => 3,
next => nil, # not a circular list
);
var A = Hash.new(
data => 1,
next => B,
);
var C = Hash.new(
data => 2,
);
insert_after(A, C); |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Stata | Stata |
proc insertIntoList {existingList predecessor newElement} {
upvar $existingList exList
set exList [linsert $exList [expr [lsearch -exact $exList $predecessor] + 1] $newElement]
}
set list {A B}
insertIntoList list A C
puts $list
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
print("Enter number of milliseconds to sleep: ")
val ms = readLine()!!.toLong()
println("Sleeping...")
Thread.sleep(ms)
println("Awake!")
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #LabVIEW | LabVIEW | stdoutnl('Sleeping...')
sleep(5000) // Sleep 5 seconds
stdoutnl('Awake!') |
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #Java | Java | import java.io.*;
public class SierpinskiSquareCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) {
SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);
int size = 635, length = 5;
s.currentAngle = 0;
s.currentX = (size - length)/2;
s.currentY = length;
s.lineLength = length;
s.begin(size);
s.execute(rewrite(5));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private SierpinskiSquareCurve(final Writer writer) {
this.writer = writer;
}
private void begin(final int size) throws IOException {
write("<svg xmlns='http://www.w3.org/2000/svg' width='%d' height='%d'>\n", size, size);
write("<rect width='100%%' height='100%%' fill='white'/>\n");
write("<path stroke-width='1' stroke='black' fill='none' d='");
}
private void end() throws IOException {
write("'/>\n</svg>\n");
}
private void execute(final String s) throws IOException {
write("M%g,%g\n", currentX, currentY);
for (int i = 0, n = s.length(); i < n; ++i) {
switch (s.charAt(i)) {
case 'F':
line(lineLength);
break;
case '+':
turn(ANGLE);
break;
case '-':
turn(-ANGLE);
break;
}
}
}
private void line(final double length) throws IOException {
final double theta = (Math.PI * currentAngle) / 180.0;
currentX += length * Math.cos(theta);
currentY += length * Math.sin(theta);
write("L%g,%g\n", currentX, currentY);
}
private void turn(final int angle) {
currentAngle = (currentAngle + angle) % 360;
}
private void write(final String format, final Object... args) throws IOException {
writer.write(String.format(format, args));
}
private static String rewrite(final int order) {
String s = AXIOM;
for (int i = 0; i < order; ++i) {
final StringBuilder sb = new StringBuilder();
for (int j = 0, n = s.length(); j < n; ++j) {
final char ch = s.charAt(j);
if (ch == 'X')
sb.append(PRODUCTION);
else
sb.append(ch);
}
s = sb.toString();
}
return s;
}
private final Writer writer;
private double lineLength;
private double currentX;
private double currentY;
private int currentAngle;
private static final String AXIOM = "F+XF+F+XF";
private static final String PRODUCTION = "XF-F+F-XF+F+XF-F+F-X";
private static final int ANGLE = 90;
} |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #FutureBasic | FutureBasic | _window = 1
begin enum 1
_label
_clickMeBtn
end enum
void local fn BuildWindow
window _window, @"Simple Windowed Application", (0,0,366,59)
textlabel _label, @"There have been no clicks yet", (18,23,250,16)
button _clickMeBtn,,, @"Click Me", (267,13,86,32)
end fn
void local fn ButtonClicked
static long clickCount = 0
clickCount++
textlabel _label, fn StringWithFormat( @"The button has been clicked %ld times", clickCount )
end fn
void local fn DoDialog( ev as long, tag as long )
select ( ev )
case _btnClick
select ( tag )
case _clickMeBtn : fn ButtonClicked
end select
end select
end fn
fn BuildWindow
on dialog fn DoDialog
HandleEvents |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Gambas | Gambas | iCount As Integer 'Counter of clicks!
hLabel As Label 'We need a Label
Public Sub Form_Open()
Dim hButton As Button 'We need a Button
With Me 'Set the Form's Properties..
.height = 75 'Set the Height
.Width = 300 'Set the Width
.Arrangement = Arrange.Vertical 'Arrange items vertically
.Padding = 5 'Border area
.Title = "Click counter!" 'Title displayed on the Form
End With
hlabel = New Label(Me) 'Add a Label to the form
With hlabel 'Set the Label's Properties..
.expand = True 'Expand the Label to fit the Form
.Text = "There have been no clicks yet" 'Add Text to the Label
.Alignment = Align.Center 'Center the Text
End With
hButton = New Button(Me) As "Button1" 'Add a Button to the form as Event "Button1"
With hButton 'Set the Button's Properties..
.Height = 28 'Set the Height
.Text = "&Click me" 'Add Text (The '&' adds a keyboard shortcut)
End With
End
Public Sub Button1_Click() 'When the Button is clicked..
Inc iCount 'Increase the value of iCount
hLabel.text = "The button has been clicked " & iCount & " times" 'Display the amount of clicks"
End |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Ruby | Ruby | head = ListNode.new("a", ListNode.new("b", ListNode.new("c")))
head.insertAfter("b", "b+")
# then:
head.each {|node| print node.value, ","}
puts
# or
current = head
begin
print current.value, ","
end while current = current.succ
puts |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Run_BASIC | Run BASIC | list$ = "now is the time for all good men"
for lnk = 1 to 8
print lnk;"->";word$(list$,lnk)
next lnk |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Tcl | Tcl |
proc insertIntoList {existingList predecessor newElement} {
upvar $existingList exList
set exList [linsert $exList [expr [lsearch -exact $exList $predecessor] + 1] $newElement]
}
set list {A B}
insertIntoList list A C
puts $list
|
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Wren | Wren | import "/llist" for LinkedList
var ll = LinkedList.new(["A", "B"])
ll.insertAfter("A", "C")
System.print(ll) |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Lasso | Lasso | stdoutnl('Sleeping...')
sleep(5000) // Sleep 5 seconds
stdoutnl('Awake!') |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Lhogho | Lhogho | make "Void "V0
make "Long "U4
make "kernel32_handle libload "kernel32.dll
to Sleep :dwMilliseconds
end
external "Sleep [ Void Sleep Long] :kernel32_handle
to millisleep :n
print [Sleeping...]
Sleep :n ; units: 1/1000th of a second
print [Awake.]
end |
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #jq | jq | include "simple-turtle" {search: "."};
def rules: {"X": "XF-F+F-XF+F+XF-F+F-X"};
def sierpinski($count):
rules as $rules
| def p($count):
if $count <= 0 then .
else gsub("X"; $rules["X"]) | p($count-1)
end;
"F+XF+F+XF" | p($count) ;
def interpret($x):
if $x == "+" then turtleRotate(90)
elif $x == "-" then turtleRotate(-90)
elif $x == "F" then turtleForward(5)
else .
end;
def sierpinski_curve($n):
sierpinski($n)
| split("")
| reduce .[] as $action (turtle([200,650]) | turtleDown;
interpret($action) ) ;
sierpinski_curve(5)
| path("none"; "red"; 1) | svg(1000)
|
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #Julia | Julia | using Lindenmayer # https://github.com/cormullion/Lindenmayer.jl
scurve = LSystem(Dict("X" => "XF-F+F-XF+F+XF-F+F-X"), "F+XF+F+XF")
drawLSystem(scurve,
forward = 3,
turn = 90,
startingy = -400,
iterations = 6,
filename = "sierpinski_square_curve.png",
showpreview = true
)
|
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Graphics[SierpinskiCurve[3]] |
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #Nim | Nim | import math
type
SierpinskiCurve = object
x, y: float
angle: float
length: int
file: File
proc line(sc: var SierpinskiCurve) =
let theta = degToRad(sc.angle)
sc.x += sc.length.toFloat * cos(theta)
sc.y += sc.length.toFloat * sin(theta)
sc.file.write " L", sc.x, ',', sc.y
proc execute(sc: var SierpinskiCurve; s: string) =
sc.file.write 'M', sc.x, ',', sc.y
for c in s:
case c
of 'F': sc.line()
of '+': sc.angle = floorMod(sc.angle + 90, 360)
of '-': sc.angle = floorMod(sc.angle - 90, 360)
else: discard
func rewrite(s: string): string =
for c in s:
if c == 'X':
result.add "XF-F+F-XF+F+XF-F+F-X"
else:
result.add c
proc write(sc: var SierpinskiCurve; size, length, order: int) =
sc.length = length
sc.x = (size - length) / 2
sc.y = length.toFloat
sc.angle = 0
sc.file.write "<svg xmlns='http://www.w3.org/2000/svg' width='", size, "' height='", size, "'>\n"
sc.file.write "<rect width='100%' height='100%' fill='white'/>\n"
sc.file.write "<path stroke-width='1' stroke='black' fill='none' d='"
var s = "F+XF+F+XF"
for _ in 1..order: s = s.rewrite()
sc.execute(s)
sc.file.write "'/>\n</svg>\n"
let outfile = open("sierpinski_square.svg", fmWrite)
var sc = SierpinskiCurve(file: outfile)
sc.write(635, 5, 5)
outfile.close() |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Gastona | Gastona | #javaj#
<frames> main, Simple click counter
<layout of main>
PANEL, X
bClick me, lClicks
#data#
<NN> 0
<lClicks> //There have been no clicks yet
#listix#
<-- bClick me>
NUM=, NN, NN+1
-->, lClicks data!,, //@<NN> clicks so far
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Go | Go | package main
import (
"fmt"
"github.com/mattn/go-gtk/gtk"
)
func main() {
gtk.Init(nil)
window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
window.SetTitle("Click me")
label := gtk.NewLabel("There have been no clicks yet")
var clicks int
button := gtk.NewButtonWithLabel("click me")
button.Clicked(func() {
clicks++
if clicks == 1 {
label.SetLabel("Button clicked 1 time")
} else {
label.SetLabel(fmt.Sprintf("Button clicked %d times",
clicks))
}
})
vbox := gtk.NewVBox(false, 1)
vbox.Add(label)
vbox.Add(button)
window.Add(vbox)
window.Connect("destroy", func() {
gtk.MainQuit()
})
window.ShowAll()
gtk.Main()
} |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Rust | Rust | //
//
// Iteration by value (simply empties the list as the caller now owns all values)
//
//
pub struct IntoIter<T>(List<T>);
impl<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.0.head.take().map(|node| {
let node = *node;
self.0.head = node.next;
node.elem
})
}
}
//
//
// Iteration by immutable reference
//
//
pub struct Iter<'a, T: 'a> {
next: Option<&'a Node<T>>,
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.next.take().map(|node| {
self.next = node.next.as_ref().map(|node| &**node);
&node.elem
})
}
}
//
//
// Iteration by mutable reference
//
//
pub struct IterMut<'a, T: 'a> {
next: Option<&'a mut Node<T>>,
}
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
self.next.take().map(|node| {
self.next = node.next.as_mut().map(|node| &mut **node);
&mut node.elem
})
}
}
//
//
// Methods implemented for List<T>
//
//
impl<T> List<T> {
pub fn into_iter(self) -> IntoIter<T> {
IntoIter(self)
}
pub fn iter<'a>(&'a self) -> Iter<'a,T> {
Iter { next: self.head.as_ref().map(|node| &**node) }
}
pub fn iter_mut(&mut self) -> IterMut<T> {
IterMut { next: self.head.as_mut().map(|node| &mut **node) }
}
} |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Scala | Scala |
/*
Here is a basic list definition
sealed trait List[+A]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]
*/
def traverse[A](as: List[A]): Unit = as match {
case Nil => print("End")
case Cons(h, t) => {
print(h + " ")
traverse(t)
}
}
|
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #X86_Assembly | X86 Assembly |
; x86_64 Linux NASM
; Linked_List_Insert.asm
%ifndef INSERT
%define INSERT
%include "Linked_List_Definition.asm" ; see LL def task
%include "Heap_Alloc.asm" ; see memory allocation task
section .text
; rdi - link to insert after
; rsi - value that the new link will hold
Insert_After:
push rdi
push rsi
mov rdi, linkSize
call alloc
cmp rax, 0
je Memory_Allocation_Failure_Exception
pop rdi
mov dword [rax + value], edi
pop rdi
mov rsi, qword [rdi + next]
mov qword [rax + next], rsi
mov qword [rdi + next], rax
ret
%endif
|
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #XPL0 | XPL0 | def \Node\ Link, Data; \linked list element definition
def IntSize = 4; \number of bytes in an integer
proc Insert(List, Node); \Insert Node into List
int List, Node;
[Node(Link):= List(Link);
List(Link):= Node;
];
int MyNode, MyList;
int A, B, C;
[A:= Reserve(2*IntSize);
B:= Reserve(2*IntSize);
C:= Reserve(2*IntSize);
A(Data):= 1;
B(Data):= 2;
C(Data):= 3;
MyList:= A; \make initial list
A(Link):= 0;
Insert(A, B); \insert node B after A
Insert(A, C); \insert node C after A
MyNode:= MyList; \traverse the linked list
while MyNode # 0 do \display the example data
[IntOut(0, MyNode(Data));
ChOut(0, ^ );
MyNode:= MyNode(Link); \move to next node
];
] |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Yabasic | Yabasic | // Rosetta Code problem: http://rosettacode.org/wiki/Singly-linked_list/Element_insertion
// by Galileo, 02/2022
FIL = 1 : DATO = 2 : LINK = 3
countNodes = 0 : Nodes = 10
dim list(Nodes, 3)
sub searchNode(node)
local i, prevNode
for i = 1 to countNodes
if i = node break
prevNode = list(prevNode, LINK)
next
return prevNode
end sub
sub insertNode(node, newNode, after)
local prevNode, i
prevNode = searchNode(node)
if after prevNode = list(prevNode, LINK)
for i = 1 to Nodes
if not list(i, FIL) break
next
list(i, FIL) = true
list(i, DATO) = newNode
list(i, LINK) = list(prevNode, LINK)
list(prevNode, LINK) = i
countNodes = countNodes + 1
if countNodes = Nodes then Nodes = Nodes + 10 : redim list(Nodes, 3) : end if
end sub
sub printNode(node)
local prevNode
prevNode = searchNode(node)
node = list(prevNode, LINK)
// print list(node, FIL);
print list(node, DATO);
// print list(node, LINK);
print
end sub
insertNode(1, 1000, true)
insertNode(1, 2000, true)
insertNode(1, 3000, true)
printNode(1)
printNode(2)
printNode(3) |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Liberty_BASIC | Liberty BASIC | Input "Please input the number of milliseconds you would like to sleep. "; sleeptime
Print "Sleeping..."
CallDLL #kernel32, "Sleep", sleeptime As long, ret As void
Print "Awake!"
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Lingo | Lingo | on doSleep (ms)
put "Sleeping..."
sleep(ms)
put "Awake!"
end |
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #Perl | Perl | use strict;
use warnings;
use SVG;
use List::Util qw(max min);
use constant pi => 2 * atan2(1, 0);
my $rule = 'XF-F+F-XF+F+XF-F+F-X';
my $S = 'F+F+XF+F+XF';
$S =~ s/X/$rule/g for 1..5;
my (@X, @Y);
my ($x, $y) = (0, 0);
my $theta = pi/4;
my $r = 6;
for (split //, $S) {
if (/F/) {
push @X, sprintf "%.0f", $x;
push @Y, sprintf "%.0f", $y;
$x += $r * cos($theta);
$y += $r * sin($theta);
}
elsif (/\+/) { $theta += pi/2; }
elsif (/\-/) { $theta -= pi/2; }
}
my ($xrng, $yrng) = ( max(@X) - min(@X), max(@Y) - min(@Y));
my ($xt, $yt) = (-min(@X) + 10, -min(@Y) + 10);
my $svg = SVG->new(width=>$xrng+20, height=>$yrng+20);
my $points = $svg->get_path(x=>\@X, y=>\@Y, -type=>'polyline');
$svg->rect(width=>"100%", height=>"100%", style=>{'fill'=>'black'});
$svg->polyline(%$points, style=>{'stroke'=>'orange', 'stroke-width'=>1}, transform=>"translate($xt,$yt)");
open my $fh, '>', 'sierpinski-square-curve.svg';
print $fh $svg->xmlify(-namespace=>'svg');
close $fh; |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Groovy | Groovy | import groovy.swing.SwingBuilder
count = 0
new SwingBuilder().edt {
frame(title:'Click frame', pack: true, show: true) {
vbox {
countLabel = label("There have been no clicks yet.")
button('Click Me', actionPerformed: {count++; countLabel.text = "Clicked ${count} time(s)."})
}
}
} |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Scheme | Scheme | (define (traverse seq func)
(if (null? seq)
'()
(begin
(func (car seq))
(traverse (cdr seq) func)))) |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Sidef | Sidef | var list = 'a':'b':'c':nil;
#var list = ['a', ['b', ['c']]];
#var list = Pair.new('a', Pair.new('b', Pair.new('c', nil)));
for (var l = list; l != nil; l = l[1]) {
say l[0];
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #zkl | zkl | L("a","b","c").insert(1,"foo") //-->L("a","foo","b","c")
a:=L("a","b","c"); a.insert(a.find("b"),"foo") //-->L("a","foo","b","c") |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Zig | Zig |
const std = @import("std");
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = arena.allocator();
pub fn LinkedList(comptime Value: type) type {
return struct {
const This = @This();
const Node = struct {
value: Value,
next: ?*Node,
};
head: ?*Node,
tail: ?*Node,
pub fn init() This {
return LinkedList(Value) {
.head = null,
.tail = null,
};
}
pub fn add(this: *This, value: Value) !void {
var newNode = try allocator.create(Node);
newNode.* = .{ .value = value, .next = null };
if (this.tail) |tail| {
tail.next = newNode;
this.tail = newNode;
} else if (this.head) |head| {
head.next = newNode;
this.tail = newNode;
} else {
this.head = newNode;
}
}
};
}
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Logo | Logo |
to sleep :n
print [Sleeping...]
wait :n ; units: 1/60th of a second
print [Awake.]
end
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Logtalk | Logtalk |
:- object(sleep).
:- public(how_long/1).
how_long(Seconds) :-
write('Sleeping ...'), nl,
thread_sleep(Seconds),
write('... awake!'), nl.
:- end_object.
|
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #Phix | Phix | --
-- demo\rosetta\Sierpinski_square_curve.exw
-- ========================================
--
-- My second atempt at a Lindenmayer system. The first
-- is now saved in demo\rosetta\Penrose_tiling.exw
--
with javascript_semantics
include pGUI.e
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
function redraw_cb(Ihandle /*canvas*/)
string s = "F+F+XF+F+XF"
for n=1 to 4 do
string next = ""
for i=1 to length(s) do
integer ch = s[i]
next &= iff(ch='X'?"XF-F+F-XF+F+XF-F+F-X":ch)
end for
s = next
end for
cdCanvasActivate(cddbuffer)
cdCanvasBegin(cddbuffer, CD_CLOSED_LINES)
atom x=0, y=0, theta=PI/4, r = 6
for i=1 to length(s) do
integer ch = s[i]
switch ch do
case 'F': x += r*cos(theta)
y += r*sin(theta)
cdCanvasVertex(cddbuffer, x+270, y+270)
case '+': theta += PI/2
case '-': theta -= PI/2
end switch
end for
cdCanvasEnd(cddbuffer)
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
function map_cb(Ihandle canvas)
cdcanvas = cdCreateCanvas(CD_IUP, canvas)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetBackground(cddbuffer, CD_WHITE)
cdCanvasSetForeground(cddbuffer, CD_BLUE)
return IUP_DEFAULT
end function
IupOpen()
canvas = IupCanvas("RASTERSIZE=290x295")
IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
"ACTION", Icallback("redraw_cb")})
dlg = IupDialog(canvas,`TITLE="Sierpinski square curve"`)
IupSetAttribute(dlg,`DIALOGFRAME`,`YES`)
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Haskell | Haskell | import Graphics.UI.Gtk
import Data.IORef
main :: IO ()
main = do
initGUI
window <- windowNew
window `onDestroy` mainQuit
windowSetTitle window "Simple Windowed App"
set window [ containerBorderWidth := 10 ]
hbox <- hBoxNew True 5
set window [ containerChild := hbox ]
lab <- labelNew (Just "There have been no clicks yet")
button <- buttonNewWithLabel "Click me"
set hbox [ containerChild := lab ]
set hbox [ containerChild := button ]
m <- newIORef 0
onClicked button $ do
v <- readIORef m
writeIORef m (v+1)
set lab [ labelText := "There have been " ++ show (v+1) ++ " clicks" ]
widgetShowAll window
mainGUI |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #SSEM | SSEM | 11101000000000100000000000000000 0. -23 to c
10011000000000010000000000000000 1. Sub. 25
10010000000001100000000000000000 2. c to 9
10101000000000010000000000000000 3. Sub. 21
11010000000001100000000000000000 4. c to 11
10010000000000100000000000000000 5. -9 to c
10010000000001100000000000000000 6. c to 9
11010000000000100000000000000000 7. -11 to c
11010000000001100000000000000000 8. c to 11
00000000000000000000000000000000 9. to be generated at run time
00101000000001100000000000000000 10. c to 20
00000000000000000000000000000000 11. to be generated at run time
00000000000000110000000000000000 12. Test
00011000000000000000000000000000 13. 24 to CI
10011000000001100000000000000000 14. c to 25
10011000000000100000000000000000 15. -25 to c
10011000000001100000000000000000 16. c to 25
01101000000000000000000000000000 17. 22 to CI
00101000000000100000000000000000 18. -20 to c
00000000000001110000000000000000 19. Stop
00000000000000000000000000000000 20. variable: negation of car
10000000000000000000000000000000 21. constant 1
11111111111111111111111111111111 22. constant -1
00000000000000100000000000000000 23. -0 to c
10001000000000000000000000000000 24. constant 17 (jump target)
00111000000000000000000000000000 25. 28 (pointer variable)
01000000000000000000000000000000 26. 2
01111000000000000000000000000000 27. pointer: 30
10000000000000000000000000000000 28. 1
01011000000000000000000000000000 29. pointer: 26
11000000000000000000000000000000 30. 3
00000000000000000000000000000000 31. 0 (nil) |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Stata | Stata | oo::define List {
method for {varName script} {
upvar 1 $varName var
set elem [self]
while {$elem ne ""} {
set var [$elem value]
uplevel 1 $script
set elem [$elem next]
}
}
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Lua | Lua | local socket = require("socket")
io.write("Input a number of seconds to sleep: ")
local input = io.read("*number")
print("Sleeping")
socket.sleep(input)
print("Awake!") |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Input "Input a number of milliseconds to sleep:", N
Print "Sleeping..."
Wait N
Print "Awake"
}
CheckIt
|
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #Python | Python | import matplotlib.pyplot as plt
import math
def nextPoint(x, y, angle):
a = math.pi * angle / 180
x2 = (int)(round(x + (1 * math.cos(a))))
y2 = (int)(round(y + (1 * math.sin(a))))
return x2, y2
def expand(axiom, rules, level):
for l in range(0, level):
a2 = ""
for c in axiom:
if c in rules:
a2 += rules[c]
else:
a2 += c
axiom = a2
return axiom
def draw_lsystem(axiom, rules, angle, iterations):
xp = [1]
yp = [1]
direction = 0
for c in expand(axiom, rules, iterations):
if c == "F":
xn, yn = nextPoint(xp[-1], yp[-1], direction)
xp.append(xn)
yp.append(yn)
elif c == "-":
direction = direction - angle
if direction < 0:
direction = 360 + direction
elif c == "+":
direction = (direction + angle) % 360
plt.plot(xp, yp)
plt.show()
if __name__ == '__main__':
# Sierpinski Square L-System Definition
s_axiom = "F+XF+F+XF"
s_rules = {"X": "XF-F+F-XF+F+XF-F+F-X"}
s_angle = 90
draw_lsystem(s_axiom, s_rules, s_angle, 3) |
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #Quackery | Quackery | [ $ "turtleduck.qky" loadfile ] now!
[ stack ] is switch.arg ( --> [ )
[ switch.arg put ] is switch ( x --> )
[ switch.arg release ] is otherwise ( --> )
[ switch.arg share
!= iff ]else[ done
otherwise ]'[ do ]done[ ] is case ( x --> )
[ $ "" swap witheach
[ nested quackery join ] ] is expand ( $ --> $ )
[ $ "L" ] is L ( $ --> $ )
[ $ "R" ] is R ( $ --> $ )
[ $ "F" ] is F ( $ --> $ )
[ $ "AFRFLFRAFLFLAFRFLFRA" ] is A ( $ --> $ )
$ "FLAFLFLAF"
4 times expand
turtle
witheach
[ switch
[ char L case [ -1 4 turn ]
char R case [ 1 4 turn ]
char F case [ 5 1 walk ]
otherwise ( ignore ) ] ] |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #HicEst | HicEst | CHARACTER label="There have been no clicks yet"
DO count = 1, 1E100 ! "forever"
DLG(Button="Click me", Width=3, TItle=label) ! Width=3 to display full length label
label = "Clicked " // count // "time(s)"
ENDDO
END |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Tcl | Tcl | oo::define List {
method for {varName script} {
upvar 1 $varName var
set elem [self]
while {$elem ne ""} {
set var [$elem value]
uplevel 1 $script
set elem [$elem next]
}
}
} |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Trith | Trith | [1 2 3 4 5] [print] each |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Maple | Maple | sleep := proc(secs)
print("Sleeping...");
Threads:-Sleep(secs);
print("Awake!");
end proc: |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Sleep[seconds_] := (Print["Sleeping..."]; Pause[seconds]; Print["Awake!"];) |
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #Raku | Raku | use SVG;
role Lindenmayer {
has %.rules;
method succ {
self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules)
}
}
my $sierpinski = 'X' but Lindenmayer( { X => 'XF-F+F-XF+F+XF-F+F-X' } );
$sierpinski++ xx 5;
my $dim = 600;
my $scale = 6;
my @points = (-80, 298);
for $sierpinski.comb {
state ($x, $y) = @points[0,1];
state $d = $scale + 0i;
when 'F' { @points.append: ($x += $d.re).round(1), ($y += $d.im).round(1) }
when /< + - >/ { $d *= "{$_}1i" }
default { }
}
my @t = @points.tail(2).clone;
my $out = './sierpinski-square-curve-perl6.svg'.IO;
$out.spurt: SVG.serialize(
svg => [
:width($dim), :height($dim),
:rect[:width<100%>, :height<100%>, :fill<black>],
:polyline[
:points((@points, map {(@t »+=» $_).clone}, ($scale,0), (0,$scale), (-$scale,0)).join: ','),
:fill<black>, :transform("rotate(45, 300, 300)"), :style<stroke:#61D4FF>,
],
:polyline[
:points(@points.map( -> $x,$y { $x, $dim - $y + 1 }).join: ','),
:fill<black>, :transform("rotate(45, 300, 300)"), :style<stroke:#61D4FF>,
],
],
); |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Icon_and_Unicon | Icon and Unicon | import gui
$include "guih.icn"
procedure main()
SimpleWindow().show_modal()
end
class SimpleWindow : Dialog(label, button, count)
method component_setup()
self.set_attribs("size=222,139")
label := Label()
label.set_pos("24", "24")
label.set_internal_alignment("l")
label.set_label("There have been no clicks yet.")
self.add(label)
button := TextButton()
button.set_pos(24, 53)
button.set_label("click me")
button.set_internal_alignment("c")
button.connect(self, "incr", ACTION_EVENT)
self.add(button)
end
method incr()
/count := 0
label.set_label("There have been "||(count+:=1)||" clicks.")
end
initially
self.Dialog.initially()
end |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Visual_Basic_.NET | Visual Basic .NET | Private Sub Iterate(ByVal list As LinkedList(Of Integer))
Dim node = list.First
Do Until node Is Nothing
node = node.Next
Loop
End Sub |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Wart | Wart | each x '(1 2 3)
prn x |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #MATLAB_.2F_Octave | MATLAB / Octave | function sleep()
time = input('How many seconds would you like me to sleep for? ');
assert(time > .01);
disp('Sleeping...');
pause(time);
disp('Awake!');
end |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #min | min | "Enter number of milliseconds to sleep" ask int
"Sleeping..." puts!
sleep
"Awake!" puts! |
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #Rust | Rust | // [dependencies]
// svg = "0.8.0"
use svg::node::element::path::Data;
use svg::node::element::Path;
struct SierpinskiSquareCurve {
current_x: f64,
current_y: f64,
current_angle: i32,
line_length: f64,
}
impl SierpinskiSquareCurve {
fn new(x: f64, y: f64, length: f64, angle: i32) -> SierpinskiSquareCurve {
SierpinskiSquareCurve {
current_x: x,
current_y: y,
current_angle: angle,
line_length: length,
}
}
fn rewrite(order: usize) -> String {
let mut str = String::from("F+XF+F+XF");
for _ in 0..order {
let mut tmp = String::new();
for ch in str.chars() {
match ch {
'X' => tmp.push_str("XF-F+F-XF+F+XF-F+F-X"),
_ => tmp.push(ch),
}
}
str = tmp;
}
str
}
fn execute(&mut self, order: usize) -> Path {
let mut data = Data::new().move_to((self.current_x, self.current_y));
for ch in SierpinskiSquareCurve::rewrite(order).chars() {
match ch {
'F' => data = self.draw_line(data),
'+' => self.turn(90),
'-' => self.turn(-90),
_ => {}
}
}
Path::new()
.set("fill", "none")
.set("stroke", "black")
.set("stroke-width", "1")
.set("d", data)
}
fn draw_line(&mut self, data: Data) -> Data {
let theta = (self.current_angle as f64).to_radians();
self.current_x += self.line_length * theta.cos();
self.current_y += self.line_length * theta.sin();
data.line_to((self.current_x, self.current_y))
}
fn turn(&mut self, angle: i32) {
self.current_angle = (self.current_angle + angle) % 360;
}
fn save(file: &str, size: usize, length: f64, order: usize) -> std::io::Result<()> {
use svg::node::element::Rectangle;
let x = (size as f64 - length) / 2.0;
let y = length;
let rect = Rectangle::new()
.set("width", "100%")
.set("height", "100%")
.set("fill", "white");
let mut s = SierpinskiSquareCurve::new(x, y, length, 0);
let document = svg::Document::new()
.set("width", size)
.set("height", size)
.add(rect)
.add(s.execute(order));
svg::save(file, &document)
}
}
fn main() {
SierpinskiSquareCurve::save("sierpinski_square_curve.svg", 635, 5.0, 5).unwrap();
} |
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #Sidef | Sidef | var rules = Hash(
x => 'xF-F+F-xF+F+xF-F+F-x',
)
var lsys = LSystem(
width: 510,
height: 510,
xoff: -505,
yoff: -254,
len: 4,
angle: 90,
color: 'dark green',
)
lsys.execute('F+xF+F+xF', 5, "sierpiński_square_curve.png", rules) |
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
import "math" for Math
import "./lsystem" for LSystem, Rule
var TwoPi = Num.pi * 2
class SierpinskiSquareCurve {
construct new(width, height, back, fore) {
Window.title = "Sierpinski Square Curve"
Window.resize(width, height)
Canvas.resize(width, height)
_w = width
_h = height
_bc = back
_fc = fore
}
init() {
Canvas.cls(_bc)
var cx = 10
var cy = (_h/2).floor + 5
var theta = 0
var h = 6
var lsys = LSystem.new(
["X"], // variables
["F", "+", "-"], // constants
"F+XF+F+XF", // axiom
[Rule.new("X", "XF-F+F-XF+F+XF-F+F-X")], // rules
Num.pi / 2 // angle (90 degrees in radians)
)
var result = lsys.iterate(5)
var operations = {
"F": Fn.new {
var newX = cx + h*Math.sin(theta)
var newY = cy - h*Math.cos(theta)
Canvas.line(cx, cy, newX, newY, _fc, 2)
cx = newX
cy = newY
},
"+": Fn.new {
theta = (theta + lsys.angle) % TwoPi
},
"-": Fn.new {
theta = (theta - lsys.angle) % TwoPi
}
}
LSystem.execute(result, operations)
}
update() {}
draw(alpha) {}
}
var Game = SierpinskiSquareCurve.new(770, 770, Color.blue, Color.yellow) |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #IDL | IDL | pro counter, ev
widget_control, ev.top, get_uvalue=tst
tst[1] = tst[1]+1
widget_control, tst[0], set_value="Number of clicks: "+string(tst[1],format='(i0)')
widget_control, ev.top, set_uvalue=tst
end
id = widget_base(title = 'Window Title',column=1)
ld = widget_label(id, value = 'There have been no clicks yet.')
widget_control, /realize, id, set_uvalue=[ld,0]
dummy = widget_button(id,value=' Click Me ',event_pro='counter')
xmanager, "Simple", Id
end |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Wren | Wren | import "/llist" for LinkedList
import "/fmt" for Fmt
//create a new linked list and add the first 50 positive integers to it
var ll = LinkedList.new(1..50)
// traverse the linked list
for (i in ll) {
Fmt.write("$4d ", i)
if (i % 10 == 0) System.print()
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Nanoquery | Nanoquery | time = int(input("time to sleep (ms): "))
println "Sleeping..."
sleep(time)
println "Awake!" |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Nemerle | Nemerle | using System;
using System.Console;
using System.Threading.Thread; // this is where the Sleep() method comes from
module Zzzz
{
Main() : void
{
def nap_time = Int32.Parse(ReadLine());
WriteLine("Sleeping...");
Sleep(nap_time); // parameter is time in milliseconds
WriteLine("Awake!");
}
} |
http://rosettacode.org/wiki/Sierpinski_square_curve | Sierpinski square curve |
Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
| #zkl | zkl | sierpinskiSquareCurve(4) : turtle(_);
fcn sierpinskiSquareCurve(n){ // Lindenmayer system --> Data of As
var [const] A="AF-F+F-AF+F+AF-F+F-A", B=""; // Production rules
var [const] Axiom="F+AF+F+AF";
buf1,buf2 := Data(Void,Axiom).howza(3), Data().howza(3); // characters
do(n){
buf1.pump(buf2.clear(),fcn(c){ if(c=="A") A else if(c=="B") B else c });
t:=buf1; buf1=buf2; buf2=t; // swap buffers
}
buf1 // n=4 --> 3,239 characters
}
fcn turtle(curve){ // a "square" turtle, directions are +-90*
const D=10;
ds,dir := T( T(D,0), T(0,-D), T(-D,0), T(0,D) ), 2; // turtle offsets
dx,dy := ds[dir];
img,color := PPM(650,650), 0x00ff00; // green on black
x,y := img.w/2, 10;
curve.replace("A","").replace("B",""); // A & B are no-op during drawing
foreach c in (curve){
switch(c){
case("F"){ img.line(x,y, (x+=dx),(y+=dy), color) } // draw forward
case("+"){ dir=(dir+1)%4; dx,dy = ds[dir] } // turn right 90*
case("-"){ dir=(dir-1)%4; dx,dy = ds[dir] } // turn left 90*
}
}
img.writeJPGFile("sierpinskiSquareCurve.zkl.jpg");
} |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #J | J | SIMPLEAPP=: noun define
pc simpleApp;
cc inc button;cn "Click me";
cc shownText static;cn "There have been no clicks yet.";
)
simpleApp_run=: verb define
wd SIMPLEAPP
simpleApp_accum=: 0 NB. initialize accumulator
wd 'pshow;'
)
simpleApp_inc_button=: verb define
wd 'set shownText text ','Button-use count: ',": simpleApp_accum=: >: simpleApp_accum
)
simpleApp_close=: wd bind 'pclose'
simpleApp_cancel=: simpleApp_close
simpleApp_run'' |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #XPL0 | XPL0 | def \Node\ Link, Data; \linked list element definition
int Node, List;
[Node:= List; \traverse the linked list
while Node # 0 do
Node:= Node(Link); \move to next node
] |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Yabasic | Yabasic | // Rosetta Code problem: http://rosettacode.org/wiki/Singly-linked_list/Element_insertion & removal & traverse
// by Galileo, 02/2022
FIL = 1 : DATO = 2 : LINK = 3
countNodes = 0 : Nodes = 10
dim list(Nodes, 3)
sub searchNode(node)
local i, prevNode
for i = 1 to countNodes
if i = node break
prevNode = list(prevNode, LINK)
next
return prevNode
end sub
sub insertNode(node, newNode, after)
local prevNode, i
prevNode = searchNode(node)
if after prevNode = list(prevNode, LINK)
for i = 1 to Nodes
if not list(i, FIL) break
next
list(i, FIL) = true
list(i, DATO) = newNode
list(i, LINK) = list(prevNode, LINK)
list(prevNode, LINK) = i
countNodes = countNodes + 1
if countNodes = Nodes then Nodes = Nodes + 10 : redim list(Nodes, 3) : end if
end sub
sub removeNode(n)
local prevNode, node
prevNode = searchNode(n)
node = list(prevNode, LINK)
list(prevNode, LINK) = list(node, LINK)
list(node, FIL) = false
countNodes = countNodes - 1
end sub
sub printNode(node)
local prevNode
prevNode = searchNode(node)
node = list(prevNode, LINK)
print list(node, DATO);
print
end sub
sub traverseList()
local i
for i = 1 to countNodes
printNode(i)
next
end sub
insertNode(1, 1000, true)
insertNode(1, 2000, true)
insertNode(1, 3000, true)
traverseList()
removeNode(2)
print
traverseList()
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method sleep(secs) public static binary
ms = (secs * 1000).format(null, 0) -- milliseconds, rounded to nearest integer
say 'Sleeping...'
do
Thread.sleep(ms)
catch ix = InterruptedException
say 'Sleep interrupted!'
ix.printStackTrace()
end
say 'Awake!'
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
secs = -1
loop until \secs.datatype('N')
if secs > 0 then do
say 'Napping for' secs's'
say
sleep(secs)
end
say
say 'How many seconds do you want me to sleep? (enter something non-numeric to terminate)\-'
parse ask secs .
say
end
say
say 'Goodbye...'
say
return
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Java | Java | import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class Clicks extends JFrame{
private long clicks = 0;
public Clicks(){
super("Clicks");//set window title
JLabel label = new JLabel("There have been no clicks yet");
JButton clicker = new JButton("click me");
clicker.addActionListener(//listen to the button
new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
label.setText("There have been " + (++clicks) + " clicks");//change the text
}
}
);
setLayout(new BorderLayout());//handles placement of components
add(label,BorderLayout.CENTER);//add the label to the biggest section
add(clicker,BorderLayout.SOUTH);//put the button underneath it
label.setPreferredSize(new Dimension(300,100));//nice big label
label.setHorizontalAlignment(JLabel.CENTER);//text not up against the side
pack();//fix layout
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//stop the program on "X"
setVisible(true);//show it
}
public static void main(String[] args){
SwingUtilities.invokeLater( //Swing UI updates should not happen on the main thread
() -> new Clicks() //call the constructor where all the magic happens
);
}
} |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Zig | Zig | const std = @import("std");
pub fn main() anyerror!void {
var l1 = LinkedList(i32).init();
try l1.add(1);
try l1.add(2);
try l1.add(4);
try l1.add(3);
var h = l1.head;
while (h) |head| : (h = head.next) {
std.log.info("> {}", .{ head.value });
}
} |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #zkl | zkl | foreach n in (List(1,2,3) {...}
List(1,2,3).pump(...) // traverse and munge elements, generalized apply/map
List(1,2,3).filter(...)
List(1,2,3).filter22(...) // partition list
List(1,2,3).reduce(...)
List(1,2,3).apply(...)
List(1,2,3).sum()
List(1,2,3).run() // treat each element as f, perform f()
List(1,2,3).enumerate()
List(1,2,3).reverse()
List(1,2,3).concat()
List(1,2,3).shuffle() |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #NewLISP | NewLISP | (println "Sleeping..." )
(sleep 2000) ; Wait for 2 seconds
(println "Awake!") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.