defmodule Smith do
  def number?(n) do
    d = decomposition(n)
    length(d)>1 and sum_digits(n) == Enum.map(d, &sum_digits/1) |> Enum.sum
  end

  defp sum_digits(n) do
    Integer.digits(n) |> Enum.sum
  end

  defp decomposition(n, k\\2, acc\\[])
  defp decomposition(n, k, acc) when n < k*k, do: [n | acc]
  defp decomposition(n, k, acc) when rem(n, k) == 0, do: decomposition(div(n, k), k, [k | acc])
  defp decomposition(n, k, acc), do: decomposition(n, k+1, acc)
end

m = 10000
smith = Enum.filter(1..m, &Smith.number?/1)
IO.puts "#{length(smith)} smith numbers below #{m}:"
IO.puts "First 10: #{Enum.take(smith,10) |> Enum.join(", ")}"
IO.puts "Last  10: #{Enum.take(smith,-10) |> Enum.join(", ")}"


Collection Class new: LinkedList(data, mutable next)


list = .linkedlist~new
index = list~insert("abc")   -- insert a first item, keeping the index
list~insert("def")           -- adds to the end
list~insert("123", .nil)     -- adds to the begining
list~insert("456", index)    -- inserts between "abc" and "def"
list~remove(index)           -- removes "abc"

say "Manual list traversal"
index = list~first           -- demonstrate traversal
loop while index \== .nil
    say index~value
    index = index~next
end

say
say "Do ... Over traversal"
do value over list
    say value
end

-- the main list item, holding the anchor to the links.
::class linkedlist
::method init
  expose anchor

  -- create this as an empty list
  anchor = .nil

-- return first link element
::method first
  expose anchor
  return anchor

-- return last link element
::method last
  expose anchor

  current = anchor
  loop while current \= .nil
      -- found the last one
      if current~next == .nil then return current
      current = current~next
  end
  -- empty
  return .nil

-- insert a value into the list, using the convention
-- followed by the built-in list class.  If the index item
-- is omitted, add to the end.  If the index item is .nil,
-- add to the end.  Otherwise, just chain to the provided link.
::method insert
  expose anchor
  use arg value

  newLink = .link~new(value)
  -- adding to the end
  if arg() == 1 then do
      if anchor == .nil then anchor = newLink
      else self~last~insert(newLink)
  end
  else do
      use arg ,index
      if index == .nil then do
         if anchor \== .nil then newLink~next = anchor
         anchor = newLink
      end
      else index~insert(newLink)
  end
  -- the link item serves as an "index"
  return newLink

-- remove a link from the chain
::method remove
  expose anchor

  use strict arg index

  -- handle the edge case
  if index == anchor then anchor = anchor~next
  else do
      -- no back link, so we need to scan
      previous = self~findPrevious(index)
      -- invalid index, don't return any item
      if previous == .nil then return .nil
      previous~next = index~next
  end
  -- belt-and-braces, remove the link and return the value
  index~next = .nil
  return index~value

-- private method to find a link predecessor
::method findPrevious private
  expose anchor
  use strict arg index

  -- we're our own precessor if this first
  if index == anchor then return self

  current = anchor
  loop while current \== .nil
      if current~next == index then return current
      current = current~next
  end
  -- not found
  return .nil

-- helper method to allow DO ... OVER traversal
::method makearray
  expose anchor
  array = .array~new

  current = anchor
  loop while current \= .nil
      array~append(current~value)
      current = current~next
  end
  return array

::class link
::method init
  expose value next
  -- by default, initialize both data and next to empty.
  use strict arg value = .nil, next = .nil

-- allow external access to value and next link
::attribute value
::attribute next

::method insert
  expose next
  use strict arg newNode
  newNode~next = next
  next = newNode


type
  PLink = ^TLink;
  TLink = record
    FNext: PLink;
    FData: integer;
  end;


class SnakeGame(w, h) {
    const readkey = frequire('Term::ReadKey')
    const ansi    = frequire('Term::ANSIColor')

    enum (VOID, HEAD, BODY, TAIL, FOOD)

    define (
        LEFT  = [+0, -1],
        RIGHT = [+0, +1],
        UP    = [-1, +0],
        DOWN  = [+1, +0],
    )

    define BG_COLOR    = "on_black"
    define FOOD_COLOR  = ("red"        + " " + BG_COLOR)
    define SNAKE_COLOR = ("bold green" + " " + BG_COLOR)
    define SLEEP_SEC   = 0.02

    const (
        A_VOID  = ansi.colored(' ', BG_COLOR),
        A_FOOD  = ansi.colored('❇', FOOD_COLOR),
        A_BLOCK = ansi.colored('■', SNAKE_COLOR),
    )

    has dir = LEFT
    has grid = [[]]
    has head_pos = [0, 0]
    has tail_pos = [0, 0]

    method init {
        grid = h.of { w.of { [VOID] } }

        head_pos = [h//2, w//2]
        tail_pos = [head_pos[0], head_pos[1]+1]

        grid[head_pos[0]][head_pos[1]] = [HEAD, dir]    # head
        grid[tail_pos[0]][tail_pos[1]] = [TAIL, dir]    # tail

        self.make_food()
    }

    method make_food {
        var (food_x, food_y)

        do {
            food_x = w.rand.int
            food_y = h.rand.int
        } while (grid[food_y][food_x][0] != VOID)

        grid[food_y][food_x][0] = FOOD
    }

    method display {
        print("\033[H", grid.map { |row|
            row.map { |cell|
                given (cell[0]) {
                    when (VOID) { A_VOID }
                    when (FOOD) { A_FOOD }
                    default     { A_BLOCK }
                }
              }.join('')
            }.join("\n")
        )
    }

    method move {
        var grew = false

        # Move the head
        var (y, x) = head_pos...

        var new_y = (y+dir[0] % h)
        var new_x = (x+dir[1] % w)

        var cell = grid[new_y][new_x]

        given (cell[0]) {
            when (BODY) { die "\nYou just bit your own body!\n" }
            when (TAIL) { die "\nYou just bit your own tail!\n" }
            when (FOOD) { grew = true; self.make_food()         }
        }

        # Create a new head
        grid[new_y][new_x] = [HEAD, dir]

        # Replace the current head with body
        grid[y][x] = [BODY, dir]

        # Update the head position
        head_pos = [new_y, new_x]

        # Move the tail
        if (!grew) {
            var (y, x) = tail_pos...

            var pos   = grid[y][x][1]
            var new_y = (y+pos[0] % h)
            var new_x = (x+pos[1] % w)

            grid[y][x][0]         = VOID    # erase the current tail
            grid[new_y][new_x][0] = TAIL    # create a new tail

            tail_pos = [new_y, new_x]
        }
    }

    method play {
        STDOUT.autoflush(true)
        readkey.ReadMode(3)

        try {
            loop {
                var key
                while (!defined(key = readkey.ReadLine(-1))) {
                    self.move()
                    self.display()
                    Sys.sleep(SLEEP_SEC)
                }

                given (key) {
                    when ("\e[A") { if (dir != DOWN ) { dir = UP    } }
                    when ("\e[B") { if (dir != UP   ) { dir = DOWN  } }
                    when ("\e[C") { if (dir != LEFT ) { dir = RIGHT } }
                    when ("\e[D") { if (dir != RIGHT) { dir = LEFT  } }
                }
            }
        }
        catch {
            readkey.ReadMode(0)
        }
    }
}

var w = `tput cols`.to_i
var h = `tput lines`.to_i

SnakeGame(w || 80, h || 24).play


         START
         PRINT DATA,GEN
         YREGS ,                      REGISTER EQUATES (e.g. 0 = R0)
SLEEP    CSECT
SLEEP    AMODE 31                     addressing mode 31 bit
SLEEP    RMODE ANY                    loader determines 31 or 24
***********************************************************************
* REENTRANT. Logically swap out a task for a number of seconds
*            specified in PARM. Minimum 0, maximum 60 seconds
*
* MVS rexx (the original rexx) does not have a sleep function. This
* program can be called from rexx, assuming this program is in
* LINKLIST, as follows:
*
*         /* rexx */
*         wait_time = '6' /* number of seconds to sleep */
*         say 'Sleeping...'
*         address LINKMVS "SLEEP wait_time"  /* invoke SLEEP */
*         say 'Awake!
***********************************************************************
PROLOG   BAKR  R14,0                 satck caller's registers
         LR    R4,R1                 save parm pointer
         LR    R12,R15               entry point addr to R12
         USING SLEEP,R12             tell assembler about that
         B     AROUND                avoid abend S0C1
         DC    C'SLEEP '             CSECT NAME
         DC    C'C=2014.05.10 '      CHANGE DATE
         DC    C'A=&SYSDATE '        ASSEMBLY DATE
         DC    C'T=&SYSTIME '        CHANGE TIME
         DC    C'MarcvdM. '          PROGRAMMER NAME
AROUND   L     R10,0(0,R4)           load parm address in R10
         XR    R15,R15               clear R15
         LH    R15,0(0,R10)          load parm length in R15
         LR    R6,R15                save length in R6
         LTR   R15,R15               parm length 0?
         BZ    NOPARM                yes, exit before getmain
         C     R6,F2                 parmlength > 2 ?
         BH    NOPARM                yes, exit before getmain
        STORAGE OBTAIN,LENGTH=WALEN,LOC=ANY  get some storage
         LR    R9,R1                 address of storage in R9
         USING WAREAX,R9             base for data section (DSECT)
         MVC   EYECAT,=C'**MARC**'   make storage easy to find in dump
         MVC   SECONDS,C00           set field to F0F0
         C     R6,F1                 parmlength = 1?
         BNE   COPYSECS              no, copy both bytes
         MVC   SECONDS+1(1),2(R10)   yes, just copy one byte.
         B     TRTEST
COPYSECS MVC   SECONDS,2(R10)
* test supplied parameter for valid integer values
TRTEST   TRT   SECONDS(1),VALINT6    first parm byte no higher as 6?
         BNZ   NOPARM_REL            higher, release storage and return
         TRT   SECONDS+1(1),VALINT9  second byte valid?
         BNZ   NOPARM_REL            no, release storage and return
         CLC   SECONDS(1),=C'6'      first parm byte < 6?
         BNE   DOWAIT                yes, do wait
         CLC   SECONDS+1(1),=C'0'    first eq. 6, second > 0?
         BNE   NOPARM_REL            yes, release storage and return
DOWAIT   DS    0H
         MVC   WAWTO(DWTOL),DWTO     copy WTO list form to obtained st.
         MVC   WAWTO+18(2),SECONDS   copy in nr. of seconds
        WTO    MF=(E,WAWTO)          issue WTO, execute form
         MVC   HOURS,C00             zero out hours
         MVC   MINUTS,C00             and minutes
         MVC   REST,C00                and milliseconds
        STIMER WAIT,DINTVL=TIMEVAL   SVC 47: logical swap out (sleep)
         B     EXIT                  done
NOPARM_REL DS  0H
        STORAGE RELEASE,ADDR=(R9),LENGTH=WALEN  free obtained storage
         LA    R15,4                 set return code 4
         B     RETURN                return to caller
EXIT     DS    0H
        STORAGE RELEASE,ADDR=(R9),LENGTH=WALEN  free obtained storage
        WTO    ' Awake!',ROUTCDE=11   fixed wake-up string
NOPARM   EQU   *
RETURN   PR    ,                     return to caller
*
* --------------------------------------------------------------------
* CONSTANTS
* --------------------------------------------------------------------
DWTO     WTO    ' Sleeping... (XX seconds)',ROUTCDE=11,MF=L
DWTOL     EQU   *-DWTO             length of WTO list form
F1        DC    F'1'
F2        DC    F'2'
C00       DC    C'00'
VALINT6   DC    256XL1'01'
          ORG   *-16
VALOK6    DC    7XL1'00'           F0-F6: OFFSETS 240-246
VALINT9   DC    256XL1'01'
          ORG   *-16
VALOK9    DC    10XL1'00'          F0-F9: OFFSETS 240-249
          DS    0D
         LTORG ,                   FORCE DISPLACEMENT LITERALS
* --------------------------------------------------------------------
* DSECT (data section)
* --------------------------------------------------------------------
WAREAX   DSECT ,
WAWTO    DS    CL(DWTOL)           reentrant WTO area
EYECAT   DS    CL8
TIMEVAL  DS    0CL8
HOURS    DS    CL2                 will be zeroed
MINUTS   DS    CL2                 will be zeroed
SECONDS  DS    CL2                 from parm
REST     DS    CL2                 will be zeroed
WALEN    EQU   *-WAREAX            length of DSECT
* --------------------------------------------------------------------
         END   SLEEP


ORG RESET
	jmp main
ORG TIMER0
	; timer interrupt only used to wake the processor
	clr tr0
	reti

main:
	setb ea		; enable interrupts
	setb et0	; enable timer0 interrupt
	mov tl0, #0	; start timer counter at zero
	mov th0, #0	; these two values dictate the length of sleep

	mov a, pcon	; copy power control register
	setb a.0	; set idl bit
	setb tr0	; start timer
	; sleeping...
	mov pcon, a	; move a back into pcon (processor sleeps after this instruction finishes)

	; when the timer overflows and the timer interrupt returns, execution will resume at this spot

	; Awake!
	jmp $


f:stdin f:getline
"Sleeping..." . cr
eval sleep
"Awake!" . cr bye


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program sleep64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"

.equ SLEEP,  0x65                        // Linux syscall

.equ BUFFERSIZE,         100
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessQuest:             .asciz "Enter the time to sleep in seconds : "
szMessError:             .asciz "Error occured.\n"
szMessSleep:             .asciz "Sleeping Zzzzzzz.\n"
szMessAwake:             .asciz "Awake!!!\n"

szCarriageReturn:        .asciz "\n"
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
.align 4
ZonesAttente:
  qSecondes:      .skip 8
  qMicroSecondes: .skip 8
ZonesTemps:       .skip 16
sBuffer:          .skip BUFFERSIZE
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:
    ldr x0,qAdrszMessQuest            // display invite message
    bl affichageMess
    mov x0,STDIN                      // input standard linux
    ldr x1,qAdrsBuffer
    mov x2,BUFFERSIZE
    mov x8,READ                       // read input string
    svc 0
    cmp x0,0                          // read error ?
    ble 99f
    //
    ldr x0,qAdrsBuffer                // buffer address
    bl conversionAtoD                 // conversion string in number in x0

    ldr x1,qAdrqSecondes
    str x0,[x1]                       // store second number in area
    ldr x0,qAdrszMessSleep            // display sleeping message
    bl affichageMess
    ldr x0,qAdrZonesAttente           // delay area
    ldr x1,qAdrZonesTemps             //
    mov x8,#SLEEP                     // call system SLEEP
    svc 0
    cmp x0,#0                         // error sleep ?
    blt 99f
    ldr x0,qAdrszMessAwake            // display awake message
    bl affichageMess
    mov x0, #0                        // return code
    b 100f
99:                                   // display error message
    ldr x0,qAdrszMessError
    bl affichageMess
    mov x0, 1                         // return code

100:                                  // standard end of the program
    mov x8,EXIT                       // request to exit program
    svc 0                             // perform system call
qAdrszMessQuest:          .quad szMessQuest
qAdrszMessError:          .quad szMessError
qAdrszMessSleep:          .quad szMessSleep
qAdrszMessAwake:          .quad szMessAwake
qAdrqSecondes:            .quad qSecondes
qAdrZonesAttente:         .quad ZonesAttente
qAdrZonesTemps:           .quad ZonesTemps
qAdrsBuffer:              .quad sBuffer
qAdrszCarriageReturn:     .quad szCarriageReturn
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


BYTE RTCLOK1=$13
BYTE RTCLOK2=$14
BYTE PALNTSC=$D014

PROC Wait(CARD frames)
  BYTE lsb=frames,msb=frames+1

  ;wait lsb of frames
  lsb==+RTCLOK2
  WHILE lsb#RTCLOK2 DO OD

  ;wait msb of 256*frames
  WHILE msb>0
  DO
    WHILE lsb=RTCLOK2 DO OD
    WHILE lsb#RTCLOK2 DO OD
    msb==-1
  OD
RETURN

CARD FUNC GetFrame()
  CARD res
  BYTE lsb=res,msb=res+1

  lsb=RTCLOK2
  msb=RTCLOK1
RETURN (res)

CARD FUNC MsToFrames(CARD ms)
  CARD res

  IF PALNTSC=15 THEN
    res=ms/60
  ELSE
    res=ms/50
  FI
RETURN (res)

CARD FUNC FramesToMs(CARD frames)
  CARD res

  IF PALNTSC=15 THEN
    res=frames*60
  ELSE
    res=frames*50
  FI
RETURN (res)

PROC Main()
  CARD ARRAY data=[1 5 10 50 100 500]
  CARD beg,end,diff,diffMs,delay,delayMs
  BYTE i

  FOR i=0 TO 5
  DO
    delay=data(i)
    delayMs=FramesToMs(delay)
    PrintF("Wait %U frames / %U ms...%E",delay,delayMs)

    beg=GetFrame()
    Wait(delay)
    end=GetFrame()
    diff=end-beg
    diffMs=FramesToMs(diff)

    PrintF("Frame number at begin %U%E",beg)
    PrintF("Frame number at end %U%E",end)
    PrintF("Waited %U-%U=%U frames / %U ms%E%E",end,beg,diff,diffMs)
  OD
RETURN


// Generate Smith Numbers. Nigel Galloway: November 6th., 2020
let fN g=Seq.unfold(fun n->match n with 0->None |_->Some(n%10,n/10)) g |> Seq.sum
let rec fG(n,g) p=match g%p with 0->fG (n+fN p,g/p) p |_->(n,g)
primes32()|>Seq.pairwise|>Seq.collect(fun(n,g)->[n+1..g-1])|>Seq.takeWhile(fun n->n<10000)
|>Seq.filter(fun g->fN g=fst(primes32()|>Seq.scan(fun n g->fG n g)(0,g)|>Seq.find(fun(_,n)->n=1)))
|>Seq.chunkBySize 20|>Seq.iter(fun n->Seq.iter(printf "%4d ") n; printfn "")


USING: formatting grouping io kernel math.primes.factors
math.ranges math.text.utils sequences sequences.deep ;

: (smith?) ( n factors -- ? )
    [ 1 digit-groups sum ]
    [ [ 1 digit-groups ] map flatten sum = ] bi* ; inline

: smith? ( n -- ? )
    dup factors dup length 1 = [ 2drop f ] [ (smith?) ] if ;

10,000 [1,b] [ smith? ] filter 10 group
[ [ "%4d " printf ] each nl ] each


my %node = (
    data => 'say what',
    next => \%foo_node,
);
$node{next} = \%bar_node;  # mutable


enum NEXT,DATA
type slnode(object x)
    return (sequence(x) and length(x)=DATA and myotherudt(x[DATA]) and integer(x[NEXT])
end type


declare 1 node based (p),
          2 value fixed,
          2 link pointer;


;;; Use shorthand syntax to create list.
lvars l1 = [1 2 three 'four'];
;;; Allocate a single list node, with value field 1 and the link field
;;; pointing to empty list
lvars l2 = cons(1, []);
;;; print first element of l1
front(l1) =>
;;; print the rest of l1
back(l1) =>
;;; Use index notation to access third element
l1(3) =>
;;; modify link field of l2 to point to l1
l1 -> back(l2);
;;; Print l2
l2 =>


Structure MyData
  *next.MyData
  Value.i
EndStructure


class LinkedList(object):
     """USELESS academic/classroom example of a linked list implemented in Python.
        Don't ever consider using something this crude!  Use the built-in list() type!
     """
	class Node(object):
		def __init__(self, item):
			self.value  = item
			self.next = None
	def __init__(self, item=None):
		if item is not None:
			self.head = Node(item); self.tail = self.head
		else:
			self.head = None; self.tail = None
	def append(self, item):
		if not self.head:
			self.head = Node(item)
			self.tail = self.head
		elif self.tail:
			self.tail.next = Node(item)
			self.tail = self.tail.next
		else:
			self.tail = Node(item)
	def __iter__(self):
		cursor = self.head
		while cursor:
			yield cursor.value
			cursor = cursor.next


*        Singly-linked list - Insert after  01/02/2017
LISTSINA CSECT
         USING  LISTSINA,R13       base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         STM    R14,R12,12(R13)    prolog
         ST     R13,4(R15)         " <-
         ST     R15,8(R13)         " ->
         LR     R13,R15            " addressability
*        Allocate A
         GETMAIN RU,LV=12          get storage
         USING  NODE,R11           make storage addressable
         LR     R11,R1             "
         MVC    VAL,=CL8'A'        val='A'
         MVC    NEXT,=A(0)
         DROP   R11                base no longer needed
         ST     R11,A              [email protected]
*        Init LIST
         ST     R11,LIST           init LIST with A
*        Allocate C
         GETMAIN RU,LV=12          get storage
         USING  NODE,R11           make storage addressable
         LR     R11,R1             "
         MVC    VAL,=CL8'C'        val='C'
         MVC    NEXT,=A(0)
         DROP   R11                base no longer needed
         ST     R11,C              [email protected]
*        Insert C After A
         MVC    P1,A
         MVC    P2,C
         LA     R1,PARML
         BAL    R14,INSERTAF
*        Allocate B
         GETMAIN RU,LV=12          get storage
         USING  NODE,R11           make storage addressable
         LR     R11,R1             "
         MVC    VAL,=CL8'B'        val='B'
         MVC    NEXT,=A(0)
         DROP   R11                base no longer needed
         ST     R11,B              [email protected]
*        Insert B After A
         MVC    P1,A
         MVC    P2,B
         LA     R1,PARML
         BAL    R14,INSERTAF
*        List all
         L      R11,LIST
         USING  NODE,R11           address node
LOOP     C      R11,=A(0)
         BE     ENDLIST
         XPRNT  VAL,8
         L      R11,NEXT
         B      LOOP
ENDLIST  DROP   R11
         FREEMAIN A=A,LV=12        free A
         FREEMAIN A=B,LV=12        free B
         FREEMAIN A=C,LV=12        free C
RETURN   L      R13,4(0,R13)       epilog
         LM     R14,R12,12(R13)    " restore
         XR     R15,R15            " rc=0
         BR     R14                exit
LIST     DS     A                  list head
A        DS     A
B        DS     A
C        DS     A
PARML    DS     0A
P1       DS     A
P2       DS     A
INSERTAF CNOP   0,4
         L      R2,0(R1)           @A
         L      R3,4(R1)           @B
         USING  NODE,R2            ->A
         L      R4,NEXT            @C
         DROP   R2
         USING  NODE,R3            ->B
         ST     R4,NEXT            [email protected]
         DROP   R3
         USING  NODE,R2            ->A
         ST     R3,NEXT            [email protected]
         DROP   R2
         BR     R14                return
         LTORG                     all literals
NODE     DSECT                     node (size=12)
VAL      DS     CL8
NEXT     DS     A
         YREGS
         END    LISTSINA


/* snake.wren */

import "random" for Random
import "./dynamic" for Enum, Lower

foreign class Window {
    construct initscr() {}

    foreign nodelay(bf)
}

class Ncurses {
    foreign static cbreak()

    foreign static noecho()

    foreign static refresh()

    foreign static getch()

    foreign static mvaddch(y, x, ch)

    foreign static endwin()
}

class C {
    foreign static usleep(usec)
}

var Dir = Enum.create("Dir", ["N", "E", "S", "W"])
var State = Enum.create("State", ["space", "food", "border"])

var w = 80
var h = 40
var board = List.filled(w * h, 0)
var rand = Random.new()
var head
var dir
var quit

// ASCII values
var hash = 35
var at   = 64
var dot  = 46
var spc  = 32

/* negative values denote the snake (a negated time-to-live in given cell) */

// reduce a time-to-live, effectively erasing the tail
var age = Fn.new {
    for (i in 0...w * h) {
        if (board[i] < 0) board[i] = board[i] + 1
    }
}

// put a piece of food at random empty position
var plant = Fn.new {
    var r
    while (true) {
        r = rand.int(w * h)
        if (board[r] = State.space) break
    }
    board[r] = State.food
}

// initialize the board, plant a very first food item
var start = Fn.new {
    for (i in 0...w) board[i] = board[i + (h - 1) * w] = State.border
    for (i in 0...h) board[i * w] = board[i * w + w - 1] = State.border
    head = (w * (h - 1 - h % 2) / 2).floor  // screen center for any h
    board[head] = -5
    dir = Dir.N
    quit = false
    plant.call()
}

var step = Fn.new {
    var len = board[head]
    if (dir == Dir.N) {
        head = head - w
    } else if (dir == Dir.S) {
        head = head + w
    } else if (dir == Dir.W) {
        head = head - 1
    } else if (dir == Dir.E) {
        head =  head + 1
    }

    if (board[head] == State.space) {
        board[head] = len - 1  // keep in mind len is negative
        age.call()
    } else if (board[head] == State.food) {
        board[head] = len - 1
        plant.call()
    } else {
        quit = true
    }
}

var show = Fn.new {
    var symbol = [spc, at, dot]
    for (i in 0...w*h) {
        Ncurses.mvaddch((i/w).floor, i % w, board[i] < 0 ? hash : symbol[board[i]])
    }
    Ncurses.refresh()
}

var initScreen = Fn.new {
    var win = Window.initscr()
    Ncurses.cbreak()
    Ncurses.noecho()
    win.nodelay(true)
}

initScreen.call()
start.call()
while (true) {
    show.call()
    var ch = Ncurses.getch()
    if (ch == Lower.i) {
        dir = Dir.N
    } else if (ch == Lower.j) {
        dir = Dir.W
    } else if (ch == Lower.k) {
        dir = Dir.S
    } else if (ch == Lower.l) {
        dir = Dir.E
    } else if (ch == Lower.q) {
        quit = true
    }
    step.call()
    C.usleep(300 * 1000)  // 300 ms is a reasonable delay
    if (quit) break
}
C.usleep(999 * 1000)
Ncurses.endwin()


with Ada.Text_Io; use Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;

procedure Sleep is
   In_Val : Float;
begin
   Get(In_Val);
   Put_Line("Sleeping...");
   delay Duration(In_Val);
   Put_Line("Awake!");
end Sleep;


o_text("Sleeping...\n");

# Sleep X seconds
sleep(atoi(argv(1)));

# Sleep X microseconds
#usleep(atoi(argv(1)));

o_text("Awake!\n");


# using ping to sleep #
INT milliseconds = read int; # ping uses milliseconds #
print ("Sleeping...");
VOID (system ("ping 0.0.0.1 -n 1 -w " + whole (milliseconds, 0) + " >NUL"));
# 0.0.0.1 is an invalid IP address and cannot be used, so this will never conflict with a real IP address #
# ping -n gives number of tries, -w timeout, and >NUL deletes output so the user does not see it #
print (new line);
print ("Awake!")


milliseconds: eval[input["How long should I sleep? "]] / eval = evil, but this is just a simple demo
echo["Sleeping..."]
sleep[milliseconds]
echo["Awake!"]


      MODULE FACTORISE	!Produce a little list...
       USE PRIMEBAG		!This is a common need.
       INTEGER LASTP		!Some size allowances.
       PARAMETER (LASTP = 9)	!2*3*5*7*11*13*17*19*23*29 = 6,469,693,230, > 2,147,483,647.
       TYPE FACTORED		!Represent a number fully factored.
        INTEGER PVAL(0:LASTP)	!As a list of prime number indices with PVAL(0) the count.
        INTEGER PPOW(LASTP)	!And the powers. for the fingered primes.
       END TYPE FACTORED	!Rather than as a simple number multiplied out.

       CONTAINS		!Now for the details.
        SUBROUTINE SHOWFACTORS(N)	!First, to show an internal data structure.
         TYPE(FACTORED) N	!It is supplied as a list of prime factors.
         INTEGER I		!A stepper.
          DO I = 1,N.PVAL(0)	!Step along the list.
            IF (I.GT.1) WRITE (MSG,"('x',$)")	!Append a glyph for "multiply".
            WRITE (MSG,"(I0,$)") N.PVAL(I)	!The prime number's value.
            IF (N.PPOW(I).GT.1) WRITE (MSG,"('^',I0,$)") N.PPOW(I)	!With an interesting power?
          END DO		!On to the next element in the list.
          WRITE (MSG,1) N.PVAL(0)	!End the line
    1     FORMAT (": Factor count ",I0)	!With a count of prime factors.
        END SUBROUTINE SHOWFACTORS	!Hopefully, this will not be needed often.

        TYPE(FACTORED) FUNCTION FACTOR(IT)	!Into a list of primes and their powers.
Careful! 1 is not a factor of N, but if N is prime, N is. N = product of its prime factors.
         INTEGER IT,N	!The number and a similar style copy to damage.
         INTEGER F,FP	!A factor and a power.
          IF (IT.LE.0) STOP "Factor only positive numbers!"	!Or else...
          FACTOR.PVAL(0) = 0	!No prime factors have been found. One need not apply.
          F = 0			!NEXTPRIME(F) will return 2, the first factor to try.
          N = IT		!A copy I can damage.
Collapse N into its prime factors.
   10     DO WHILE(N.GT.1)	!Carthaga delenda est?
            IF (ISPRIME(N)) THEN!If the remnant is a prime number,
              F = N			!Then it is the last factor.
              FP = 1			!Its power is one.
              N = 1			!And the reduction is finished.
             ELSE		!Otherwise, continue trying larger factors.
              FP = 0			!It has no power yet.
   11         F = NEXTPRIME(F)		!Go for the next possible factor.
              DO WHILE(MOD(N,F).EQ.0)	!Well?
                FP = FP + 1			!Count a factor..
                N = N/F				!Reduce the number.
              END DO			!Until F's multiplicity is exhausted.
              IF (FP.LE.0) GO TO 11	!No presence? Try the next factor: N has some...
            END IF		!One way or another, F is a prime factor and FP its power.
            IF (FACTOR.PVAL(0).GE.LASTP) THEN	!Have I room in the list?
              WRITE (MSG,1) IT,LASTP		!Alas.
    1         FORMAT ("Factoring ",I0," but with provision for only ",	!This shouldn't happen,
     1         I0," distinct prime factors!")	!If LASTP is correct for the current INTEGER size.
              CALL SHOWFACTORS(FACTOR)		!Show what has been found so far.
              STOP "Not enough storage!"	!Quite.
            END IF			!But normally,
            FACTOR.PVAL(0) = FACTOR.PVAL(0) + 1	!Admit another factor.
            FACTOR.PVAL(FACTOR.PVAL(0)) = F	!The prime number found to be a factor.
            FACTOR.PPOW(FACTOR.PVAL(0)) = FP	!Place its power.
          END DO		!Now seee what has survived.
        END FUNCTION FACTOR	!Thus, a list of primes and their powers.
      END MODULE FACTORISE	!Careful! PVAL(0) is the number of prime factors.

      MODULE SMITHSTUFF	!Now for the strange stuff.
       CONTAINS		!The two special workers.
        INTEGER FUNCTION DIGITSUM(N,BASE)	!Sums the digits of N.
         INTEGER N,IT	!The number, and a copy I can damage.
         INTEGER BASE	!The base for arithmetic,
         IF (N.LT.0) STOP "DigitSum: negative numbers need not apply!"
          DIGITSUM = 0	!Here we go.
          IT = N	!This value will be damaged.
          DO WHILE(IT.GT.0)	!Something remains?
            DIGITSUM = MOD(IT,BASE) + DIGITSUM	!Yes. Grap the low-order digit.
            IT = IT/BASE			!And descend a power.
          END DO		!Perhaps something still remains.
        END FUNCTION DIGITSUM	!Numerology.

        LOGICAL FUNCTION SMITHNUM(N,BASE)	!Worse numerology.
         USE FACTORISE		!To find the prime factord of N.
         INTEGER N		!The number of interest.
         INTEGER BASE		!The base of the numerology.
         TYPE(FACTORED) F	!A list.
         INTEGER I,FD		!Assistants.
          F = FACTOR(N)		!Hopefully, LASTP is large enough for N.
c          write (6,"(a,I0,1x)",advance="no") "N=",N
c          call ShowFactors(F)
          FD = 0		!Attempts via the SUM facility involved too many requirements.
          DO I = 1,F.PVAL(0)	!For each of the prime factors found...
            FD = DIGITSUM(F.PVAL(I),BASE)*F.PPOW(I) + FD	!Not forgetting the multiplicity.
          END DO		!On to the next prime factor in the list.
          SMITHNUM = FD.EQ.DIGITSUM(N,BASE)	!This is the rule.
        END FUNCTION SMITHNUM	!So, is N a joker?
      END MODULE SMITHSTUFF	!Simple enough.

      USE PRIMEBAG	!Gain access to GRASPPRIMEBAG.
      USE SMITHSTUFF	!The special stuff.
      INTEGER LAST		!Might as well document this.
      PARAMETER (LAST = 9999)	!The specification is BELOW 10000...
      INTEGER I,N,BASE		!Workers.
      INTEGER NB,BAG(20)	!Prepare a line's worth of results.
      MSG = 6	!Standard output.

      WRITE (MSG,1) LAST	!Hello.
    1 FORMAT ('To find the "Smith" numbers up to ',I0)
      IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file!"	!Attempt in hope.

   10 DO BASE = 2,12	!Flexible numerology.
        WRITE (MSG,11) BASE	!Here we go again.
   11   FORMAT (/,"Working in base ",I0)
        N = 0			!None found.
        NB = 0			!So, none are bagged.
        DO I = 1,LAST		!Step through the span.
          IF (ISPRIME(I)) CYCLE		!Prime numbers are boring Smith numbers. Skip them.
          IF (SMITHNUM(I,BASE)) THEN	!So?
            N = N + 1				!Count one in.
            IF (NB.GE.20) THEN			!A full line's worth with another to come?
              WRITE (MSG,12) BAG			!Yep. Roll the line to make space.
   12         FORMAT (20I6)				!This will do for a nice table.
              NB = 0					!The line is now ready.
            END IF				!So much for a line buffer.
            NB = NB + 1				!Count another entry.
            BAG(NB) = I				!Place it.
          END IF			!So much for a Smith style number.
        END DO			!On to the next candidate number.
        WRITE (MSG,12) BAG(1:NB)!Wave the tail end.
        WRITE (MSG,13) N	!Save the human some counting.
   13   FORMAT (I9," found.")	!Just in case.
      END DO		!On to the next base.
      END	!That was strange.


#lang racket
(mcons 1 (mcons 2 (mcons 3 '()))) ; a mutable list


/*REXX program demonstrates how to create and show a single-linked list.*/
@.=0                                   /*define a null linked list.     */
call [email protected] 3                            /*linked list:  12 Proth Primes. */
call [email protected] 5
call [email protected] 13
call [email protected] 17
call [email protected] 41
call [email protected] 97
call [email protected] 113
call [email protected] 193
call [email protected] 241
call [email protected] 257
call [email protected] 353
call [email protected] 449
[email protected].max_width                          /*use the maximum width of nums. */
call [email protected]                             /*list all the elements in list. */
exit                                   /*stick a fork in it, we're done.*/
/*──────────────────────────────────[email protected] subroutine────────────────────*/
[email protected]: 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].p._next
        end   /*j*/
return
/*──────────────────────────────────[email protected] subroutine─────────────────────*/
[email protected]: procedure expose @.; parse arg y /*get element to be added to list*/
[email protected]._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. */


class ListNode
  attr_accessor :value, :succ

  def initialize(value, succ=nil)
    self.value = value
    self.succ = succ
  end

  def each(&b)
    yield self
    succ.each(&b) if succ
  end

  include Enumerable

  def self.from_array(ary)
    head = self.new(ary[0], nil)
    prev = head
    ary[1..-1].each do |val|
      node = self.new(val, nil)
      prev.succ = node
      prev = node
    end
    head
  end
end

list = ListNode.from_array([1,2,3,4])


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program insertList64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ NBELEMENTS,      100              // list size

/*******************************************/
/* Structures                               */
/********************************************/
/* structure linkedlist*/
    .struct  0
llist_next:                            // next element
    .struct  llist_next + 8
llist_value:                           // element value
    .struct  llist_value + 8
llist_fin:
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessInitListe:         .asciz "List initialized.\n"
szCarriageReturn:        .asciz "\n"
/* datas error display */
szMessErreur:        .asciz "Error detected.\n"
/* datas message display */
szMessResult:        .asciz "Element No : @ value : @ \n"
sZoneConv:           .skip 100
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
lList1:              .skip llist_fin * NBELEMENTS    // list memory place

/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:
    ldr x0,qAdrlList1
    mov x1,#0                           // list init
    str x1,[x0,#llist_next]
    ldr x0,qAdrszMessInitListe
    bl affichageMess
    ldr x0,qAdrlList1
    mov x1,#2
    bl insertElement                    // add element value 2
    ldr x0,qAdrlList1
    mov x1,#5
    bl insertElement                    // add element value 5
    //
    ldr x3,qAdrlList1
    mov x2,#0                           // ident element
1:
    ldr x0,[x3,#llist_next]             // end list ?
    cmp x0,#0
    beq 100f                            // yes
    add x2,x2,#1
    mov x0,x2                           // display No element and value
    ldr x1,qAdrsZoneConv
    bl conversion10S
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc
    mov x5,x0                          // address of new string
    ldr x0,[x3,#llist_value]
    ldr x1,qAdrsZoneConv
    bl conversion10S
    mov x0,x5                          // new address of message
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc
    bl affichageMess
    ldr x3,[x3,#llist_next]             // next element
    b 1b                                // and loop

100:                                    // standard end of the program
    mov x8, #EXIT                       // request to exit program
    svc 0                               // perform system call
qAdrszMessInitListe:       .quad szMessInitListe
qAdrszMessErreur:          .quad szMessErreur
qAdrszCarriageReturn:      .quad szCarriageReturn
qAdrlList1:                .quad lList1
qAdrszMessResult:          .quad szMessResult
qAdrsZoneConv:             .quad sZoneConv

/******************************************************************/
/*     insert element at end of list                          */
/******************************************************************/
/* x0 contains the address of the list */
/* x1 contains the value of element  */
/* x0 returns address of element or - 1 if error */
insertElement:
    stp x1,lr,[sp,-16]!                   // save  registers
    stp x2,x3,[sp,-16]!                   // save  registers
    mov x2,#llist_fin * NBELEMENTS
    add x2,x2,x0                             // compute address end list
1:                                        // start loop
    ldr x3,[x0,#llist_next]               // load next pointer
    cmp x3,#0                             // = zero
    csel  x0,x3,x0,ne
    bne 1b                                // no -> loop with pointer
    add x3,x0,#llist_fin                  // yes -> compute next free address
    cmp x3,x2                             // > list end
    bge 99f                               // yes -> error
    str x3,[x0,#llist_next]               // store next address in current pointer
    str x1,[x0,#llist_value]              // store element value
    mov x1,#0
    str x1,[x3,#llist_next]               // init next pointer in next address
    b 100f
99:                                       // error
    mov x0,-1
100:
    ldp x2,x3,[sp],16                     // restaur  2 registers
    ldp x1,lr,[sp],16                     // restaur  2 registers
    ret                                   // return to address lr x30
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


(defun insert-after (x e xs)
   (cond ((endp xs)
          nil)
         ((equal x (first xs))
          (cons (first xs)
                (cons e (rest xs))))
         (t (cons (first xs)
                  (insert-after x e (rest xs))))))


package
{
	public class Node
	{
		public var data:Object = null;
		public var link:Node = null;

		public function insert(node:Node):void
		{
			node.link = link;
			link = node;
		}
	}
}


with Ada.Unchecked_Deallocation;
-- Define the link type
procedure Singly_Linked is

   type Link;
   type Link_Access is access Link;
   type Link is record
      Data : Integer;
      Next : Link_Access := null;
   end record;
   -- Instantiate the generic deallocator for the link type
   procedure Free is new Ada.Unchecked_Deallocation(Link, Link_Access);

   -- Define the procedure
   procedure Insert_Append(Anchor : Link_Access; Newbie : Link_Access) is
   begin
      if Anchor /= null and Newbie /= null then
         Newbie.Next := Anchor.Next;
         Anchor.Next := Newbie;
      end if;
   end Insert_Append;

   -- Create the link elements
   A : Link_Access := new Link'(1, null);
   B : Link_Access := new Link'(2, null);
   C : Link_Access := new Link'(3, null);
-- Execute the program
begin
   Insert_Append(A, B);
   Insert_Append(A, C);
   Free(A);
   Free(B);
   Free(C);
end Singly_Linked;


def     Width=40, Height=25-1,          \playing area including border
        StartLength = 10,               \starting length of snake including head
        Morsels = 10;                   \number of food items constantly offered
int     Heading;                        \direction snake is heading
def     Up, Down, Left, Right;
int     Length,                         \current length of snake including head
        Score;                          \number of food items eaten
char    SnakeX(10000),                  \location of each segment including head
        SnakeY(10000),                  \ample room to grow
        FoodX(Morsels), FoodY(Morsels); \location of each food item
def     Black, Blue, Green, Cyan, Red, Magenta, Brown, White,  \attribute colors
        Gray, LBlue, LGreen, LCyan, LRed, LMagenta, Yellow, BWhite; \EGA palette

proc    PlaceFood(N);                   \Place Nth food item in playing area
int     N;
[FoodX(N):= Ran(Width-3) + 1;           \pick random location inside borders
 FoodY(N):= Ran(Height-3) + 1;
Cursor(FoodX(N), FoodY(N));             \show food
Attrib(Red<<4+LRed);
ChOut(6, ^@);
];      \PlaceFood

int     X, Y, I, C;
[SetVid($01);                           \set 40x25 text mode
ShowCursor(false);                      \turn off flashing cursor

Attrib(Blue<<4+LBlue);                  \show borders
Cursor(0, 0);
for X:= 0 to Width-1 do ChOut(6, ^+);
Cursor(0, Height-1);
for X:= 0 to Width-1 do ChOut(6, ^+);
for Y:= 0 to Height-1 do
    [Cursor(0, Y);  ChOut(6, ^+);
     Cursor(Width-1, Y);  ChOut(6, ^+);
    ];
Attrib(Black<<4+White);                 \show initial score
Cursor(0, 24);
Text(6, "Score: 0");
Score:= 0;

SnakeX(0):= Width/2;                    \start snake head at center
SnakeY(0):= Height/2;
Heading:= Left;
Length:= StartLength;
for I:= 1 to Length-1 do                \segments follow head to the right
    [SnakeX(I):= SnakeX(I-1) + 1;
     SnakeY(I):= SnakeY(I-1);
    ];
for I:= 0 to Morsels-1 do PlaceFood(I); \sow some tasty food

\Continuously move snake
loop \--------------------------------------------------------------------------
[Attrib(Black<<4+White);                \remove tail-end segment
Cursor(SnakeX(Length-1), SnakeY(Length-1));
ChOut(6, ^ );
Attrib(Green<<4+Yellow);                \add segment at head location
Cursor(SnakeX(0), SnakeY(0));
ChOut(6, ^#);

\Shift coordinates toward tail (+1 in case a segment gets added)
for I:= Length downto 1 do              \segment behind head gets head's coords
    [SnakeX(I):= SnakeX(I-1);
     SnakeY(I):= SnakeY(I-1);
    ];
if ChkKey then                          \key hit--get new movement direction
    [repeat C:= ChIn(1) until C # 0;    \remove arrow keys' prefix byte
    case C of
          $1B:  exit;                   \Escape, and scan codes for arrow keys
          $48:  if Heading # Down then Heading:= Up;
          $50:  if Heading # Up then Heading:= Down;
          $4B:  if Heading # Right then Heading:= Left;
          $4D:  if Heading # Left then Heading:= Right
    other       [];                     \ignore any other keystrokes
    ];
case Heading of                         \move head to its new location
  Up:   SnakeY(0):= SnakeY(0)-1;
  Down: SnakeY(0):= SnakeY(0)+1;
  Left: SnakeX(0):= SnakeX(0)-1;
  Right:SnakeX(0):= SnakeX(0)+1
other   [];
Cursor(SnakeX(0), SnakeY(0));           \show head at its new location
ChOut(6, ^8);

for I:= 0 to Morsels-1 do
    if SnakeX(0)=FoodX(I) & SnakeY(0)=FoodY(I) then
        [Score:= Score+1;               \ate a morsel
        Attrib(Black<<4+White);
        Cursor(7, 24);
        IntOut(6, Score*10);
        PlaceFood(I);                   \replenish morsel
        Length:= Length+1;              \grow snake one segment
        I:= Morsels;                    \over eating can be bad--quit for loop
        Sound(1, 1, 1500);              \BURP!
        Sound(1, 1, 1000);
        ];
if I = Morsels then Sound(0, 2, 1);     \no sound adds delay of 2/18th second

if SnakeX(0)=0 or SnakeX(0)=Width-1 or
   SnakeY(0)=0 or SnakeY(0)=Height-1 then
        quit;                           \snake hit border--game over
for I:= 1 to Length-1 do
    if SnakeX(0)=SnakeX(I) & SnakeY(0)=SnakeY(I) then
        quit;                           \snake bit itself--game over
]; \loop -----------------------------------------------------------------------
for I:= 1 to 8 do Sound(1, 1, 4000*I);  \death dirge
Sound(0, 36, 1);                        \pause 2 seconds to see result
OpenI(1);                               \flush any pending keystrokes
]


 10  POKE 768,169: POKE 770,76
 20  POKE 771,168: POKE 772,252
 30  INPUT "ENTER WAIT VALUE (1-256) : ";A
 40  IF A < 1 OR A > 256 THEN 30
 50  POKE 769,(A < 256) * A
 60  LET C = (26 + 27 * A + 5 * A ^ 2) / 2
 70  PRINT "WAIT FOR "C" CYCLES OR "
 80  PRINT C * 14 / 14.318181" MICROSECONDS"
 90  PRINT "SLEEPING": CALL 768: PRINT "AWAKE"


/* ARM assembly Raspberry PI  */
/*  program sleepAsm.s   */

/* Constantes    */
.equ STDIN,  0                           @ Linux input console
.equ STDOUT, 1                           @ Linux output console
.equ EXIT,   1                           @ Linux syscall
.equ READ,   3                           @ Linux syscall
.equ WRITE,  4                           @ Linux syscall
.equ SLEEP,  0xa2                        @ Linux syscall

.equ BUFFERSIZE,         100
/* Initialized data */
.data
szMessQuest:             .asciz "Enter the time to sleep in seconds : "
szMessError:             .asciz "Error occured.\n"
szMessSleep:             .asciz "Sleeping Zzzzzzz.\n"
szMessAwake:             .asciz "Awake!!!\n"

szCarriageReturn:        .asciz "\n"

/* UnInitialized data */
.bss
.align 4
ZonesAttente:
  iSecondes:      .skip 4
  iMicroSecondes: .skip 4
ZonesTemps:       .skip 8
sBuffer:          .skip BUFFERSIZE

/*  code section */
.text
.global main
main:
    ldr r0,iAdrszMessQuest            @ display invite message
    bl affichageMess
    mov r0,#STDIN                     @ input standard linux
    ldr r1,iAdrsBuffer
    mov r2,#BUFFERSIZE
    mov r7,#READ                      @ read input string
    svc 0
    cmp r0,#0                         @ read error ?
    ble 99f
    @
    ldr r0,iAdrsBuffer                @ buffer address
    bl conversionAtoD                 @ conversion string in number in r0

    ldr r1,iAdriSecondes
    str r0,[r1]                       @ store second number in area
    ldr r0,iAdrszMessSleep            @ display sleeping message
    bl affichageMess
    ldr r0,iAdrZonesAttente           @ delay area
    ldr r1,iAdrZonesTemps             @
    mov r7,#SLEEP                     @ call system SLEEP
    svc 0
    cmp r0,#0                         @ error sleep ?
    blt 99f
    ldr r0,iAdrszMessAwake            @ display awake message
    bl affichageMess
    mov r0, #0                        @ return code
    b 100f
99:                                   @ display error message
    ldr r0,iAdrszMessError
    bl affichageMess
    mov r0, #1                        @ return code

100:                                  @ standard end of the program
    mov r7, #EXIT                     @ request to exit program
    svc 0                             @ perform system call
iAdrszMessQuest:          .int szMessQuest
iAdrszMessError:          .int szMessError
iAdrszMessSleep:          .int szMessSleep
iAdrszMessAwake:          .int szMessAwake
iAdriSecondes:            .int iSecondes
iAdrZonesAttente:         .int ZonesAttente
iAdrZonesTemps:           .int ZonesTemps
iAdrsBuffer:              .int sBuffer
iAdrszCarriageReturn:     .int szCarriageReturn

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                       @ save  registers
    mov r2,#0                                   @ counter length */
1:                                              @ loop length calculation
    ldrb r1,[r0,r2]                             @ read octet start position + index
    cmp r1,#0                                   @ if 0 its over
    addne r2,r2,#1                              @ else add 1 in the length
    bne 1b                                      @ and loop
                                                @ so here r2 contains the length of the message
    mov r1,r0                                   @ address message in r1
    mov r0,#STDOUT                              @ code to write to the standard output Linux
    mov r7, #WRITE                              @ code call system "write"
    svc #0                                      @ call system
    pop {r0,r1,r2,r7,lr}                        @ restaur registers
    bx lr                                       @ return
 /******************************************************************/
/*     Convert a string to a number stored in a registry          */
/******************************************************************/
/* r0 contains the address of the area terminated by 0 or 0A */
/* r0 returns a number                           */
conversionAtoD:
    push {fp,lr}         @ save 2 registers
    push {r1-r7}         @ save others registers
    mov r1,#0
    mov r2,#10           @ factor
    mov r3,#0            @ counter
    mov r4,r0            @ save address string -> r4
    mov r6,#0            @ positive sign by default
    mov r0,#0            @ initialization to 0
1:     /* early space elimination loop */
    ldrb r5,[r4,r3]      @ loading in r5 of the byte located at the beginning + the position
    cmp r5,#0            @ end of string -> end routine
    beq 100f
    cmp r5,#0x0A         @ end of string -> end routine
    beq 100f
    cmp r5,#' '          @ space ?
    addeq r3,r3,#1       @ yes we loop by moving one byte
    beq 1b
    cmp r5,#'-'          @ first character is -
    moveq r6,#1          @  1 -> r6
    beq 3f               @ then move on to the next position
2:   /* beginning of digit processing loop */
    cmp r5,#'0'          @ character is not a number
    blt 3f
    cmp r5,#'9'          @ character is not a number
    bgt 3f
    /* character is a number */
    sub r5,#48
    ldr r1,iMaxi         @ check the overflow of the register
    cmp r0,r1
    bgt 99f              @ overflow error
    mul r0,r2,r0         @ multiply par factor 10
    add r0,r5            @ add to  r0
3:
    add r3,r3,#1         @ advance to the next position
    ldrb r5,[r4,r3]      @ load byte
    cmp r5,#0            @ end of string -> end routine
    beq 4f
    cmp r5,#0x0A            @ end of string -> end routine
    beq 4f
    b 2b                 @ loop
4:
    cmp r6,#1            @ test r6 for sign
    moveq r1,#-1
    muleq r0,r1,r0       @ if negatif, multiply par -1
    b 100f
99:  /* overflow error */
    ldr r0,=szMessErrDep
    bl   affichageMess
    mov r0,#0            @ return  zero  if error
100:
    pop {r1-r7}          @ restaur other registers
    pop {fp,lr}          @ restaur   2 registers
    bx lr                @return procedure
/* constante program */
iMaxi: .int 1073741824
szMessErrDep:  .asciz  "Too large: overflow 32 bits.\n"
.align 4


' FB 1.05.0 Win64

Sub getPrimeFactors(factors() As UInteger, n As UInteger)
  If n < 2 Then Return
  Dim factor As UInteger = 2
  Do
    If n Mod factor = 0 Then
      Redim Preserve factors(0 To UBound(factors) + 1)
      factors(UBound(factors)) = factor
      n \= factor
      If n = 1 Then Return
    Else
      ' non-prime factors will always give a remainder > 0 as their own factors have already been removed
      ' so it's not worth checking that the next potential factor is prime
      factor += 1
    End If
  Loop
End Sub

Function sumDigits(n As UInteger) As UInteger
  If n < 10 Then Return n
  Dim sum As UInteger = 0
  While n > 0
    sum += n Mod 10
    n \= 10
  Wend
  Return sum
End Function

Function isSmith(n As UInteger) As Boolean
  If n < 2 Then Return False
  Dim factors() As UInteger
  getPrimeFactors factors(), n
  If UBound(factors) = 0 Then Return False  '' n must be prime if there's only one factor
  Dim primeSum As UInteger = 0
  For i As UInteger = 0 To UBound(factors)
    primeSum += sumDigits(factors(i))
  Next
  Return sumDigits(n) = primeSum
End Function

Print "The Smith numbers below 10000 are : "
Print
Dim count As UInteger = 0
For i As UInteger = 2 To 9999
  If isSmith(i) Then
    Print Using "#####"; i;
    count += 1
  End If
Next
Print : Print
Print count; " numbers found"
Print
Print "Press any key to quit"
Sleep


 struct Node<T> {
    elem: T,
    next: Option<Box<Node<T>>>,
}


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 apply[A](as: A*): List[A] =
    if (as.isEmpty) Nil else Cons(as.head, apply(as.tail: _*))
}


var node = Hash.new(
    data => 'say what',
    next => foo_node,
);

node{:next} = bar_node;  # mutable


struct item {
	transmorphic scalar value
	pointer(struct item scalar) scalar next
}

struct list {
	pointer(struct item scalar) scalar head, tail
}


MODE STRINGLIST = STRUCT(STRING value, REF STRINGLIST next);

STRINGLIST list := ("Big",
  LOC STRINGLIST := ("fjords",
    LOC STRINGLIST := ("vex",
      LOC STRINGLIST := ("quick",
        LOC STRINGLIST := ("waltz",
          LOC STRINGLIST := ("nymph",NIL))))));

PROC insert = (REF STRINGLIST list, node)VOID: (
  next OF node := next OF list;
  next OF list := node
);

STRINGLIST very := ("VERY", NIL);

# EXAMPLE OF INSERTION #
insert(next OF next OF list, very );

REF STRINGLIST node := list;
WHILE REF STRINGLIST(node) ISNT NIL DO
  print((value OF node, space));
  node := next OF node
OD;
print((newline))


    % inserts a new value after the specified element of a list               %
    procedure insert( reference(ListI) value list
                    ; integer          value newValue
                    ) ;
        next(list) := ListI( newValue, next(list) );

    % declare a variable to hold a list                                       %
    reference(ListI) head;

    % create a list of integers                                               %
    head := ListI( 1701, ListI( 9000, ListI( 42, ListI( 90210, null ) ) ) );

    % insert a new value into the list                                        %
    insert( next(head), 4077 );


/* ARM assembly Raspberry PI  */
/*  program insertList.s   */

/* Constantes    */
.equ STDOUT, 1                           @ Linux output console
.equ EXIT,   1                           @ Linux syscall
.equ READ,   3
.equ WRITE,  4

.equ NBELEMENTS,      100                @ list size

/*******************************************/
/* Structures                               */
/********************************************/
/* structure linkedlist*/
    .struct  0
llist_next:                               @ next element
    .struct  llist_next + 4
llist_value:                              @ element value
    .struct  llist_value + 4
llist_fin:
/* Initialized data */
.data
szMessInitListe:         .asciz "List initialized.\n"
szCarriageReturn:        .asciz "\n"
/* datas error display */
szMessErreur:            .asciz "Error detected.\n"
/* datas message display */
szMessResult:            .ascii "Element No :"
sNumElement:             .space 12,' '
                         .ascii " value :  "
sValue:                  .space 12,' '
                         .asciz "\n"

/* UnInitialized data */
.bss
lList1:              .skip llist_fin * NBELEMENTS    @ list memory place
/*  code section */
.text
.global main
main:
    ldr r0,iAdrlList1
    mov r1,#0                           @ list init
    str r1,[r0,#llist_next]
    ldr r0,iAdrszMessInitListe
    bl affichageMess
    ldr r0,iAdrlList1
    mov r1,#2
    bl insertElement                    @ add element value 2
    ldr r0,iAdrlList1
    mov r1,#5
    bl insertElement                    @ add element value 5
    ldr r3,iAdrlList1
    mov r2,#0                           @ ident element
1:
    ldr r0,[r3,#llist_next]             @ end list ?
    cmp r0,#0
    beq 100f                            @ yes
    add r2,#1
    mov r0,r2                           @ display No element and value
    ldr r1,iAdrsNumElement
    bl conversion10S
    ldr r0,[r3,#llist_value]
    ldr r1,iAdrsValue
    bl conversion10S
    ldr r0,iAdrszMessResult
    bl affichageMess
    ldr r3,[r3,#llist_next]             @ next element
    b 1b                                @ and loop
100:                                    @ standard end of the program
    mov r7, #EXIT                       @ request to exit program
    svc 0                               @ perform system call
iAdrszMessInitListe:       .int szMessInitListe
iAdrszMessErreur:          .int szMessErreur
iAdrszCarriageReturn:      .int szCarriageReturn
iAdrlList1:                .int lList1
iAdrszMessResult:          .int szMessResult
iAdrsNumElement:           .int sNumElement
iAdrsValue:                .int sValue

/******************************************************************/
/*     insert element at end of list                          */
/******************************************************************/
/* r0 contains the address of the list */
/* r1 contains the value of element  */
/* r0 returns address of element or - 1 if error */
insertElement:
    push {r1-r3,lr}                       @ save  registers
    mov r2,#llist_fin * NBELEMENTS
    add r2,r0                             @ compute address end list
1:                                        @ start loop
    ldr r3,[r0,#llist_next]               @ load next pointer
    cmp r3,#0                             @ = zero
    movne r0,r3                           @ no -> loop with pointer
    bne 1b
    add r3,r0,#llist_fin                  @ yes -> compute next free address
    cmp r3,r2                             @ > list end
    movge r0,#-1                          @ yes -> error
    bge 100f
    str r3,[r0,#llist_next]               @ store next address in current pointer
    str r1,[r0,#llist_value]              @ store element value
    mov r1,#0
    str r1,[r3,#llist_next]               @ init next pointer in next address

100:
    pop {r1-r3,lr}                        @ restaur registers
    bx lr                                 @ return
/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                       @ save  registers
    mov r2,#0                                   @ counter length */
1:                                              @ loop length calculation
    ldrb r1,[r0,r2]                             @ read octet start position + index
    cmp r1,#0                                   @ if 0 its over
    addne r2,r2,#1                              @ else add 1 in the length
    bne 1b                                      @ and loop
                                                @ so here r2 contains the length of the message
    mov r1,r0                                   @ address message in r1
    mov r0,#STDOUT                              @ code to write to the standard output Linux
    mov r7, #WRITE                              @ code call system "write"
    svc #0                                      @ call system
    pop {r0,r1,r2,r7,lr}                        @ restaur registers
    bx lr                                       @ return
/***************************************************/
/*  Converting a register to a signed decimal      */
/***************************************************/
/* r0 contains value and r1 area address    */
conversion10S:
    push {r0-r4,lr}       @ save registers
    mov r2,r1             @ debut zone stockage
    mov r3,#'+'           @ par defaut le signe est +
    cmp r0,#0             @ negative number ?
    movlt r3,#'-'         @ yes
    mvnlt r0,r0           @ number inversion
    addlt r0,#1
    mov r4,#10            @ length area
1:                        @ start loop
    bl divisionpar10U
    add r1,#48            @ digit
    strb r1,[r2,r4]       @ store digit on area
    sub r4,r4,#1          @ previous position
    cmp r0,#0             @ stop if quotient = 0
    bne 1b

    strb r3,[r2,r4]       @ store signe
    subs r4,r4,#1         @ previous position
    blt  100f             @ if r4 < 0 -> end

    mov r1,#' '           @ space
2:
    strb r1,[r2,r4]       @store byte space
    subs r4,r4,#1         @ previous position
    bge 2b                @ loop if r4 > 0
100:
    pop {r0-r4,lr}        @ restaur registers
    bx lr
/***************************************************/
/*   division par 10   unsigned                    */
/***************************************************/
/* r0 dividende   */
/* r0 quotient    */
/* r1 remainder   */
divisionpar10U:
    push {r2,r3,r4, lr}
    mov r4,r0                                          @ save value
    //mov r3,#0xCCCD                                   @ r3 <- magic_number lower  raspberry 3
    //movt r3,#0xCCCC                                  @ r3 <- magic_number higter raspberry 3
    ldr r3,iMagicNumber                                @ r3 <- magic_number    raspberry 1 2
    umull r1, r2, r3, r0                               @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
    mov r0, r2, LSR #3                                 @ r2 <- r2 >> shift 3
    add r2,r0,r0, lsl #2                               @ r2 <- r0 * 5
    sub r1,r4,r2, lsl #1                               @ r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10)
    pop {r2,r3,r4,lr}
    bx lr                                              @ leave function
iMagicNumber:  	.int 0xCCCCCCCD


time: to :integer input "Enter number of milliseconds: "
print "Sleeping..."
pause time
print "Awake!"


TrayTip, sleeping, sleeping
sleep, 2000 ; 2 seconds
TrayTip, awake, awake
Msgbox, awake


#AutoIt Version: 3.2.10.0
$sleep_me=InputBox("Sleep", "Number of seconds to sleep", "10", "", -1, -1, 0, 0)
Dim $sleep_millisec=$sleep_me*1000
MsgBox(0,"Sleep","Sleeping for "&$sleep_me&" sec")
sleep ($sleep_millisec)
MsgBox(0,"Awake","... Awaking")


# syntax: GAWK -f SLEEP.AWK [seconds]
BEGIN {
    print("Sleeping...")
    loop(ARGV[1])
    print("Awake!")
    exit(0)
}
function loop(seconds,  t) {
# awk lacks a sleep mechanism, so simulate one by looping
    t = systime()
    while (systime() < t + seconds) {}
}


package main

import "fmt"

func numPrimeFactors(x uint) int {
	var p uint = 2
	var pf int
	if x == 1 {
		return 1
	}
	for {
		if (x % p) == 0 {
			pf++
			x /= p
			if x == 1 {
				return pf
			}
		} else {
			p++
		}
	}
}

func primeFactors(x uint, arr []uint) {
	var p uint = 2
	var pf int
	if x == 1 {
		arr[pf] = 1
		return
	}
	for {
		if (x % p) == 0 {
			arr[pf] = p
			pf++
			x /= p
			if x == 1 {
				return
			}
		} else {
			p++
		}
	}
}

func sumDigits(x uint) uint {
	var sum uint
	for x != 0 {
		sum += x % 10
		x /= 10
	}
	return sum
}

func sumFactors(arr []uint, size int) uint {
	var sum uint
	for a := 0; a < size; a++ {
		sum += sumDigits(arr[a])
	}
	return sum
}

func listAllSmithNumbers(maxSmith uint) {
	var arr []uint
	var a uint
	for a = 4; a < maxSmith; a++ {
		numfactors := numPrimeFactors(a)
		arr = make([]uint, numfactors)
		if numfactors < 2 {
			continue
		}
		primeFactors(a, arr)
		if sumDigits(a) == sumFactors(arr, numfactors) {
			fmt.Printf("%4d ", a)
		}
	}
}

func main() {
	const maxSmith = 10000
	fmt.Printf("All the Smith Numbers less than %d are:\n", maxSmith)
	listAllSmithNumbers(maxSmith)
	fmt.Println()
}


class Node<T>{
    var data:T?=nil
    var next:Node?=nil
    init(input:T){
        data=input
        next=nil
    }
}


oo::class create List {
    variable content next
    constructor {value {list ""}} {
        set content $value
        set next $list
    }
    method value args {
        set content {*}$args
    }
    method attach {list} {
        set next $list
    }
    method detach {} {
        set next ""
    }
    method next {} {
        return $next
    }
    method print {} {
        for {set n [self]} {$n ne ""} {set n [$n next]} {
            lappend values [$n value]
        }
        return $values
    }
}


import "/llist" for Node

var n1 = Node.new(1)
var n2 = Node.new(2)
n1.next = n2
System.print(["node 1", "data = %(n1.data)", "next = %(n1.next)"])
System.print(["node 2", "data = %(n2.data)", "next = %(n2.next)"])


; x86_64 Linux NASM
; Linked_List_Definition.asm

%ifndef LinkedListDefinition
%define LinkedListDefinition

struc link
  value: resd 1
  next: resq 1
  linkSize:
endstruc

%endif


def \Node\ Link, Data;                  \linked list element definition
int Node, List, N;
def IntSize = 4;                        \number of bytes in an integer
[List:= 0;                              \List is initially empty
for N:= 1 to 10 do                      \build linked list, starting at the end
    [Node:= Reserve(IntSize*2);         \get some memory to store Link and Data
    Node(Link):= List;
    Node(Data):= N*N;                   \insert example data
    List:= Node;                        \List now points to newly created node
    ];
Node:= List;                            \traverse the linked list
while Node # 0 do
    [IntOut(0, Node(Data));             \display the example data
    ChOut(0, ^ );
    Node:= Node(Link);                  \move to next node
    ];
]


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;
            }
        }
    };
}


(*------------------------------------------------------------------*)

(* The Rosetta Code linear list type can contain any [email protected]
   (The ‘@’ means it doesn’t have to be the size of a pointer.
   You can read {0 <= n} as ‘for all non-negative n’. *)
dataviewtype rclist_vt (vt : [email protected]+, n : int) =
| rclist_vt_nil (vt, 0)
| {0 <= n} rclist_vt_cons (vt, n + 1) of (vt, rclist_vt (vt, n))

(* A lemma one will need: lists never have negative lengths. *)
extern prfun {vt : [email protected]}
lemma_rclist_vt_param
          {n : int}
          (lst : !rclist_vt (vt, n)) :<prf> [0 <= n] void

(* Proof of the lemma. *)
primplement {vt}
lemma_rclist_vt_param lst =
  case+ lst of
  | rclist_vt_nil () => ()
  | rclist_vt_cons _ => ()

(*------------------------------------------------------------------*)

(* For simplicity, the Rosetta Code linear list insertion routine will
   be specifically for lists of ‘int’. We shall not take advantage of
   the template system. *)

(* Some things that will be needed. *)
#include "share/atspre_staload.hats"

(* The list is passed by reference and will be replaced by the new
   list. The old list is invalidated. *)
extern fun
rclist_int_insert
          {m     : int}         (* ‘for all list lengths m’ *)
          (lst   : &rclist_vt (int, m) >> (* & = pass by reference *)
                      (* The new type will be a list of the same
                         length (if no match were found) or a list
                         one longer. *)
                      [n : int | n == m || n == m + 1]
                      rclist_vt (int, n),
           after : int,
           x     : int) :<!wrt> void

implement
rclist_int_insert {m} (lst, after, x) =
  {
    (* A recursive nested function that finds the matching element
       and inserts the new node. *)
    fun
    find {k : int | 0 <= k}
         .<k>. (* Means: ‘k must uniformly decrease towards zero.’
                  If so, that is proof that ‘find’ terminates. *)
         (lst   : &rclist_vt (int, k) >>
                      [j : int | j == k || j == k + 1]
                      rclist_vt (int, j),
          after : int,
          x     : int) :<!wrt> void =
      case+ lst of
      | rclist_vt_nil () => ()  (* Not found. Do nothing *)
      | @ rclist_vt_cons (head, tail) when head = after =>
        {
          val _ = tail := rclist_vt_cons (x, tail)
          prval _ = [email protected] lst (* I need this unfolding and refolding
                                 stuff to make ‘tail’ a reference
                                 rather than a value, so I can
                                 assign to it. *)
        }
      | @ rclist_vt_cons (head, tail) =>
        {
          val _ = find (tail, after, x)
          prval _ = [email protected] lst
        }

    (* The following is needed to prove that the initial k above
       satisfies 0 <= k. *)
    prval _ = lemma_rclist_vt_param lst

    val _ = find (lst, after, x)
  }

(* Now let’s try it. *)

(* Some convenient notation. *)
#define NIL rclist_vt_nil ()
#define :: rclist_vt_cons
overload insert with rclist_int_insert

val A = 123
val B = 789
val C = 456

(* ‘var’ to make lst a mutable variable rather than a
   value (‘val’). *)
var lst = A :: B :: NIL

(* Do the insertion. *)
val () = insert (lst, A, C)

fun
loop {k : int | 0 <= k} .<k>.
     (p : !rclist_vt (int, k)) : void =
  case+ p of
  | NIL => ()
  | head :: tail =>
    begin
      println! (head);
      loop tail
    end
prval () = lemma_rclist_vt_param lst
val () = loop lst

(*------------------------------------------------------------------*)

implement
main0 () = ()


a = 1
a_next = b
b = 2
b_next = 0
c = 3
insert_after("c", "a")
Listvars
msgbox
return

insert_after(new, old)
{
  local temp
  temp := %old%_next
  %old%_next := new
  %new%_next := temp
}


Lbl INSERT
{r₁+2}ʳ→{r₂+2}ʳ
r₂→{r₁+2}ʳ
r₁
Return


      DIM node{pNext%, iData%}
      DIM a{} = node{}, b{} = node{}, c{} = node{}

      a.pNext% = b{}
      a.iData% = 123
      b.iData% = 789
      c.iData% = 456

      PROCinsert(a{}, c{})
      END

      DEF PROCinsert(here{}, new{})
      new.pNext% = here.pNext%
      here.pNext% = new{}
      ENDPROC


void insert_append (struct link *anchor, struct link *newlink) {
  newlink->next = anchor->next;
  anchor->next = newlink;
}


Disp "TIME:"
input→A
0→T
length(A)→L
For(I,1,L)
 If {A}<'0' or {A}>'9'
  Disp "NOT A NUMBER",i
  Return
 End
 T*10+{A}-'0'→T
 A++
End
Disp "SLEEPING...",i
Pause T
Disp "AWAKE",i


INPUT sec 'the SLEEP command takes seconds
PRINT "Sleeping..."
SLEEP sec
PRINT "Awake!"


@echo off
set /p Seconds=Enter the number of seconds to sleep:
set /a Seconds+=1
echo Sleeping ...
ping -n %Seconds% localhost >nul 2>&1
echo Awake!


      INPUT "Enter the time to sleep in centiseconds: " sleep%
      PRINT "Sleeping..."
      WAIT sleep%
      PRINT "Awake!"


#include <stdio.h>
#include <unistd.h>

int main()
{
  unsigned int seconds;
  scanf("%u", &seconds);
  printf("Sleeping...\n");
  sleep(seconds);
  printf("Awake!\n");
  return 0;
}


package main

import "fmt"

func numPrimeFactors(x uint) int {
	var p uint = 2
	var pf int
	if x == 1 {
		return 1
	}
	for {
		if (x % p) == 0 {
			pf++
			x /= p
			if x == 1 {
				return pf
			}
		} else {
			p++
		}
	}
}

func primeFactors(x uint, arr []uint) {
	var p uint = 2
	var pf int
	if x == 1 {
		arr[pf] = 1
		return
	}
	for {
		if (x % p) == 0 {
			arr[pf] = p
			pf++
			x /= p
			if x == 1 {
				return
			}
		} else {
			p++
		}
	}
}

func sumDigits(x uint) uint {
	var sum uint
	for x != 0 {
		sum += x % 10
		x /= 10
	}
	return sum
}

func sumFactors(arr []uint, size int) uint {
	var sum uint
	for a := 0; a < size; a++ {
		sum += sumDigits(arr[a])
	}
	return sum
}

func listAllSmithNumbers(maxSmith uint) {
	var arr []uint
	var a uint
	for a = 4; a < maxSmith; a++ {
		numfactors := numPrimeFactors(a)
		arr = make([]uint, numfactors)
		if numfactors < 2 {
			continue
		}
		primeFactors(a, arr)
		if sumDigits(a) == sumFactors(arr, numfactors) {
			fmt.Printf("%4d ", a)
		}
	}
}

func main() {
	const maxSmith = 10000
	fmt.Printf("All the Smith Numbers less than %d are:\n", maxSmith)
	listAllSmithNumbers(maxSmith)
	fmt.Println()
}


package
{
    public class Singleton
    {

        private static var instance:Singleton;

        // ActionScript does not allow private or protected constructors.
        public function Singleton(enforcer:SingletonEnforcer) {

        }

        public static function getInstance():Singleton {
            if (instance == null) instance = new Singleton(new SingletonEnforcer());
            return instance;
        }
    }
}

internal class SingletonEnforcer {}


static void InsertAfter<T>(LinkedListNode<T> prev, T value)
{
    prev.Next = new Link() { Value = value, Next = prev.Next };
}


template<typename T> void insert_after(link<T>* list_node, link<T>* new_node)
{
  new_node->next = list_node->next;
  list_node->next = new_node;
};


(defn insert-after [new old ls]
  (cond (empty? ls) ls
        (= (first ls) old) (cons old (cons new (rest ls)))
        :else (cons (first ls) (insert-after new old (rest ls)))))


(defun insert-after (new-element old-element list &key (test 'eql))
  "Return a list like list, but with new-element appearing after the
first occurence of old-element. If old-element does not appear in
list, then a list returning just new-element is returned."
  (if (endp list) (list new-element)
    (do ((head (list (first list)) (cons (first tail) head))
         (tail (rest list) (rest tail)))
        ((or (endp tail) (funcall test old-element (first head)))
         (nreconc head (cons new-element tail))))))

(defun ninsert-after (new-element old-element list &key (test 'eql))
  "Like insert-after, but modifies list in place.  If list is empty, a
new list containing just new-element is returned."
  (if (endp list) (list new-element)
    (do ((prev list next)
         (next (cdr list) (cdr next)))
        ((or (null next) (funcall test old-element (car prev)))
         (rplacd prev (cons new-element next))
         list))))


using System;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        int sleep = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Sleeping...");
        Thread.Sleep(sleep); //milliseconds
        Console.WriteLine("Awake!");
    }
}


#include <iostream>
#include <thread>
#include <chrono>
int main()
{
    unsigned long microseconds;
    std::cin >> microseconds;
    std::cout << "Sleeping..." << std::endl;
    std::this_thread::sleep_for(std::chrono::microseconds(microseconds));
    std::cout << "Awake!\n";
}


SLEEP
    ; the HANG command can use fractional seconds; the Awake line will be slightly off due to processing time
    read "How long to sleep in seconds?: ",sleep
    write !,"Sleeping... time is "_$ztime($piece($ztimestamp,",",2,2),1,2)
    hang +sleep    ; use + to cast numeric, if non-numeric will hang 0
    write !,"Awake!  Time is "_$ztime($piece($ztimestamp,",",2,2),1,2)
    quit


(defn sleep [ms] ; time in milliseconds
  (println "Sleeping...")
  (Thread/sleep ms)
  (println "Awake!"))
; call it
(sleep 1000)


import Data.Numbers.Primes (primeFactors)
import Data.List (unfoldr)
import Data.Tuple (swap)
import Data.Bool (bool)

isSmith :: Int -> Bool
isSmith n = pfs /= [n] && sumDigits n == foldr ((+) . sumDigits) 0 pfs
  where
    sumDigits = sum . baseDigits 10
    pfs = primeFactors n

baseDigits :: Int -> Int -> [Int]
baseDigits base = unfoldr remQuot
  where
    remQuot 0 = Nothing
    remQuot x = Just (swap (quotRem x base))

lowSmiths :: [Int]
lowSmiths = filter isSmith [2 .. 9999]

lowSmithCount :: Int
lowSmithCount = length lowSmiths

main :: IO ()
main =
  mapM_
    putStrLn
    [ "Count of Smith Numbers below 10k:"
    , show lowSmithCount
    , "\nFirst 15 Smith Numbers:"
    , unwords (show <$> take 15 lowSmiths)
    , "\nLast 12 Smith Numbers below 10k:"
    , unwords (show <$> drop (lowSmithCount - 12) lowSmiths)
    ]


package Global_Singleton is
   procedure Set_Data (Value : Integer);
   function Get_Data return Integer;
private
   type Instance_Type is record
      -- Define instance data elements
      Data : Integer := 0;
   end record;
   Instance : Instance_Type;
end Global_Singleton;


b1 := borg()
b2 := borg()
msgbox % "b1 is b2? " . (b1 == b2)
b1.datum := 3
msgbox % "b1.datum := 3`n...`nb1 datum: " b1.datum "`nb2 datum: " b2.datum ; is 3 also
msgbox % "b1.datum is b2.datum ? " (b1.datum == b2.datum)
return

borg(){
   static borg
   If !borg
      borg := Object("__Set", "Borg_Set"
                   , "__Get", "Borg_Get")
   return object(1, borg, "base", borg)
}

Borg_Get(brg, name)
{
  Return brg[1, name]
}

Borg_Set(brg, name, val)
{
  brg[1, name] := val
  Return val
}


#ifndef SILLY_H
#define SILLY_H

extern void JumpOverTheDog( int numberOfTimes);
extern int  PlayFetchWithDog( float weightOfStick);

#endif


public sealed class Singleton1 //Lazy: Yes ||| Thread-safe: Yes ||| Uses locking: Yes
{
    private static Singleton1 instance;
    private static readonly object lockObj = new object();

    public static Singleton1 Instance {
        get {
            lock(lockObj) {
                if (instance == null) {
                    instance = new Singleton1();
                }
            }
            return instance;
        }
    }
}


struct SLinkedNode(T) {
    T data;
    typeof(this)* next;
}

void insertAfter(T)(SLinkedNode!T* listNode, SLinkedNode!T* newNode) {
    newNode.next = listNode.next;
    listNode.next = newNode;
}

void main() {
    alias N = SLinkedNode!char;

    auto lh = new N('A', new N('B'));
    auto c = new N('C');

    // Inserts C after A, creating the (A C B) list:
    insertAfter(lh, c);

    // The GC will collect the memory.
}


// Using the same type defs from the one way list example.

Type

  // The pointer to the list structure
  pOneWayList = ^OneWayList;

  // The list structure
  OneWayList = record
                 pData : pointer ;
                 Next  : pOneWayList ;
               end;

// I will illustrate a simple function that will return a pointer to the
// new node or it will return NIL.  In this example I will always insert
// right, to keep the code clear.  Since I am using a function all operations
// for the new node will be conducted on the functions result.  This seems
// somewhat counter intuitive, but it is the simplest way to accomplish this.

Function InsertNode(VAR CurrentNode:pOneWayList): pOneWayList
begin

    // I try not to introduce different parts of the language, and keep each
    // example to just the code required.  in this case it is important to use
    // a try/except block.  In any OS that is multi-threaded and has many apps
    // running at the same time, you cannot rely on a call to check memory available
    // and then attempting to allocate.  In the time between the two, another
    // program may have grabbed the memory you were trying to get.

    Try
      // Try to allocate enough memory for a variable the size of OneWayList
      GetMem(Result,SizeOf(OneWayList));
    Except
      On EOutOfMemoryError do
         begin
           Result := NIL
           exit;
         end;
    end;

    // Initialize the variable.
    Result.Next  := NIL ;
    Reuslt.pdata := NIL ;

    // Ok now we will insert to the right.

    // Is the Next pointer of CurrentNode Nil?  If it is we are just tacking
    // on to the end of the list.

    if CurrentNode.Next = NIL then
       CurrentNode.Next := Result
    else
      // We are inserting into the middle of this list
      Begin
         Result.Next      := CurrentNode.Next ;
         CurrentNode.Next := result ;
      end;
end;


def insertAfter(head :LinkedList ? (!head.null()),
                new  :LinkedList ? (new.next().null())) {
    new.setNext(head.next())
    head.setNext(new)
}

def a := makeLink(1, empty)
def b := makeLink(2, empty)
def c := makeLink(3, empty)

insertAfter(a, b)
insertAfter(a, c)

var x := a
while (!x.null()) {
    println(x.value())
    x := x.next()
}


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Sleep-In-Seconds.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  Seconds-To-Sleep       USAGE COMP-2.

       PROCEDURE DIVISION.
           ACCEPT Seconds-To-Sleep

           DISPLAY "Sleeping..."

           CALL "C$SLEEP" USING BY CONTENT Seconds-To-Sleep

           DISPLAY "Awake!"

           GOBACK
           .


(defun test-sleep ()
  (let ((seconds (read)))
    (format t "Sleeping...~%")
    (sleep seconds)
    (format t "Awake!~%")))

(test-sleep)


import std.stdio, core.thread;

void main() {
    write("Enter a time to sleep (in seconds): ");

    long secs;
    readf(" %d", &secs);

    writeln("Sleeping...");
    Thread.sleep(dur!"seconds"(secs));
    writeln("Awake!");
}


$ amount_of_time = p1  ! hour[:[minute][:[second][.[hundredth]]]]
$ write sys$output "Sleeping..."
$ wait 'amount_of_time
$ write sys$output "Awake!"


digits=: 10&#.inv
sumdig=: +/@,@digits
notprime=: [email protected](1&p:)
smith=: #~  notprime * (=&sumdig q:)every


import java.util.*;

public class SmithNumbers {

    public static void main(String[] args) {
        for (int n = 1; n < 10_000; n++) {
            List<Integer> factors = primeFactors(n);
            if (factors.size() > 1) {
                int sum = sumDigits(n);
                for (int f : factors)
                    sum -= sumDigits(f);
                if (sum == 0)
                    System.out.println(n);
            }
        }
    }

    static List<Integer> primeFactors(int n) {
        List<Integer> result = new ArrayList<>();

        for (int i = 2; n % i == 0; n /= i)
            result.add(i);

        for (int i = 3; i * i <= n; i += 2) {
            while (n % i == 0) {
                result.add(i);
                n /= i;
            }
        }

        if (n != 1)
            result.add(n);

        return result;
    }

    static int sumDigits(int n) {
        int sum = 0;
        while (n > 0) {
            sum += (n % 10);
            n /= 10;
        }
        return sum;
    }
}


#include <stdexcept>

template <typename Self>
class singleton
{
protected:
	static Self*
		sentry;
public:
	static Self&
		instance()
	{
		return *sentry;
	}
	singleton()
	{
		if(sentry)
			throw std::logic_error("Error: attempt to instantiate a singleton over a pre-existing one!");
		sentry = (Self*)this;
	}
	virtual ~singleton()
	{
		if(sentry == this)
			sentry = 0;
	}
};
template <typename Self>
Self*
	singleton<Self>::sentry = 0;

/*
	Example usage:
*/

#include <iostream>
#include <string>

using namespace
	std;

class controller : public singleton<controller>
{
public:
	controller(string const& name)
	: name(name)
	{
		trace("begin");
	}
	~controller()
	{
		trace("end");
	}
	void
		work()
	{
		trace("doing stuff");
	}
	void
		trace(string const& message)
	{
		cout << name << ": " << message << endl;
	}
	string
		name;
};
int
	main()
{
	controller*
		first = new controller("first");
	controller::instance().work();
	delete first;
/*
	No problem, our first controller no longer exists...
*/
	controller
		second("second");
	controller::instance().work();
	try
	{
	/*
		Never happens...
	*/
		controller
			goner("goner");
		controller::instance().work();
	}
	catch(exception const& error)
	{
		cout << error.what() << endl;
	}
	controller::instance().work();
/*
	Never happens (and depending on your system this may or may not print a helpful message!)
*/
	controller
		goner("goner");
	controller::instance().work();
}


/// The <CLASS>Singleton</CLASS> class represents a global singleton object that can
/// be instantiated by multiple processes.  The 'Get' class method is used to obtain
/// an in-memory object reference and the 'Set' method is used to save any changes to
/// state.  See below for an example.
///
/// <EXAMPLE>
/// Set one=##class(Singleton).Get(,.sc)
/// Set one.GlobalProperty="Some Value"
/// Set sc=one.Set()
/// </EXAMPLE>
///
/// This class can also be extended.
Class User.Singleton Extends %SerialObject
{

Property GlobalProperty As %String;

/// Refer to <LINK href=/AboutConcurrency.html>About Concurrency</LINK> for more details
/// on the optional <var>pConcurrency</var> argument.
ClassMethod Get(pConcurrency As %Integer = -1, Output pStatus As %Status = {$$$OK}) As Singleton [ Final ]
{
	// check if singleton object already instantiated
	Set oRef = ""
	For  {
		Set oRef = $ZObjNext(oRef) If oRef = "" Quit
		If oRef.%ClassName(1) = ..%ClassName(1) Quit
	}
	If $IsObject(oRef) Quit oRef

	// determine what lock needs to be applied
	If '$IsValidNum(pConcurrency, 0, -1, 4) {
		Set pStatus = $$$ERROR($$$LockTypeInvalid, pConcurrency)
		Quit $$$NULLOREF
	}
	If pConcurrency = -1 Set pConcurrency = $Xecute("Quit "_..#DEFAULTCONCURRENCY)

	// acquire lock for global singleton object
	Set lockTO = $ZUtil(115,4), lockOK = 1
	If pConcurrency<4, pConcurrency {
		Lock +^CacheTempUser("Singleton", ..%ClassName(1))#"S":lockTO Set lockOK = $Test
	} ElseIf pConcurrency = 4 {
		Lock +^CacheTempUser("Singleton", ..%ClassName(1)):lockTO Set lockOK = $Test
	}
	If 'lockOK {
		If pConcurrency = 4 {
			Set pStatus = $$$ERROR($$$LockFailedToAcquireExclusive, ..%ClassName(1))
		} Else {
			Set pStatus = $$$ERROR($$$LockFailedToAcquireRead, ..%ClassName(1))
		}
		Quit $$$NULLOREF
	}

	// retrieve global singleton object and deserialise
	Set oId = $Get(^CacheTempUser("Singleton", ..%ClassName(1)))
	Set oRef = ..%Open(oId)  //,, .pStatus)
	If '$IsObject(oRef) Set pStatus = $$$ERROR($$$GeneralError, "Failed to load singleton object.")

	// release temporary lock
	If (pConcurrency = 1) || (pConcurrency = 2) {
		Lock -^CacheTempUser("Singleton", ..%ClassName(1))#"S"
	}

	// singleton object failed to load
	If $$$ISERR(pStatus) {
		// release retained lock
		If pConcurrency = 3 {
			Lock -^CacheTempUser("Singleton", ..%ClassName(1))#"S"
		}
		If pConcurrency = 4 {
			Lock -^CacheTempUser("Singleton", ..%ClassName(1))
		}
		Quit $$$NULLOREF
	}

	// store concurrency state and return in-memory object reference
	Set oRef.Concurrency = pConcurrency
	Quit oRef
}

Method Set() As %Status [ Final ]
{
	// check for version change
	Set oId0 = $Get(^CacheTempUser("Singleton", ..%ClassName(1)))
	Set oRef0 = ..%Open(oId0)  //,, .sc)
	If '$IsObject(oRef0) Quit $$$ERROR($$$GeneralError, "Failed to load singleton object.")
	If oRef0.Version = ..Version {
		Set ..Version = ..Version + 1
	} Else {
		Quit $$$ERROR($$$ConcurrencyVersionMismatch, ..%ClassName(1))
	}

	// serialise local singleton object and check status code
	Set sc = ..%GetSwizzleObject(,.oId) If $$$ISERR(sc) Quit sc

	// acquire exclusive lock on global singleton object
	Set lockTO = $ZUtil(115,4)
	Lock +^CacheTempUser("Singleton", ..%ClassName(1)):lockTO
	If '$Test Quit $$$ERROR($$$LockFailedToAcquireExclusive, ..%ClassName(1))

	// update global singleton object and release lock
	Set ^CacheTempUser("Singleton", ..%ClassName(1)) = oId
	Lock -^CacheTempUser("Singleton", ..%ClassName(1))
	Quit $$$OK
}

Method %OnNew() As %Status [ Final, Internal ]
{
	// do not allow constructor method to be called
	Quit $$$ERROR($$$GeneralError, "Can't instantiate directly.")
}

Method %OnConstructClone() As %Status [ Final, Internal ]
{
	// do not allow singleton object to be cloned
	Quit $$$ERROR($$$GeneralError, "Can't clone instance.")
}

Method %OnClose() As %Status [ Final, Internal ]
{
	// reference count for singleton object is now zero, so
	// release lock on global singleton object, if applicable
	If ..Concurrency = 3 Lock -^CacheTempUser("Singleton", ..%ClassName(1))#"S"
	If ..Concurrency = 4 Lock -^CacheTempUser("Singleton", ..%ClassName(1))
	Quit $$$OK
}

Property Concurrency As %Integer [ Final, Private, Transient ];

Property Version As %Integer [ Final, Private ];

}


(defgeneric concat (a b)
  (:documentation "Concatenate two phrases."))

(defclass nonempty-phrase ()
  ((text :initarg :text :reader text)))

(defmethod concat ((a nonempty-phrase) (b nonempty-phrase))
  (make-instance 'nonempty-phrase :text (concatenate 'string (text a) " " (text b))))

(defmethod concat ((a (eql 'the-empty-phrase)) b)
  b)

(defmethod concat (a (b (eql 'the-empty-phrase)))
  a)

(defun example ()
  (let ((before (make-instance 'nonempty-phrase :text "Jack"))
        (mid (make-instance 'nonempty-phrase :text "went"))
        (after (make-instance 'nonempty-phrase :text "to fetch a pail of water")))
    (dolist (p (list 'the-empty-phrase
                     (make-instance 'nonempty-phrase :text "and Jill")))
      (dolist (q (list 'the-empty-phrase
                       (make-instance 'nonempty-phrase :text "up the hill")))
        (write-line (text (reduce #'concat (list before p mid q after))))))))


(define (insert-after lst target item)
    (when (null? lst) (error "cannot insert in" null))
    (let [(sub-list (member target lst))]
        (if sub-list (set-cdr! sub-list (cons item (cdr sub-list))) ; make chirurgy if found
        (nconc lst item)))) ; else append item

(define L '(a b))
(insert-after L 'a 'c)
    L  → (a c b)
(insert-after L 'x 'y)
    L → (a c b y)


singleton linkHelper
{
    insertAfter(Link prev, IntNumber i)
    {
        prev.Next := new Link(i, prev.Next)
    }
}


-module( singly_linked_list ).

-export( [append/2, foreach/2, free/1, insert/3, new/1, task/0] ).

append( New, Start ) -> Start ! {append, New}.

foreach( Fun, Start ) -> Start ! {foreach, Fun}.

free( Element ) -> Element ! {free}.

insert( New, After, Start ) -> Start ! {insert, New, After}.

new( Data ) -> erlang:spawn( fun() -> loop( Data, nonext ) end ).

task() ->
    A = new( a ),
    B = new( b ),
    append( B, A ),
    C = new( c ),
    insert( C, A, A ),
    foreach( fun(Data) -> io:fwrite("~p~n", [Data]) end, A ).

loop( Data, Next ) ->
      My_pid = erlang:self(),
      receive
      {append, New} ->
             New_next = loop_append( New, Next ),
             loop( Data, New_next );
      {foreach, Fun} ->
                catch Fun( Data ),
		loop_foreach( Fun, Next ),
                loop( Data, Next );
      {free} ->
             ok;
      {insert, New, My_pid} ->
             append( Next, New ),
             loop( Data, New );
      {insert, New, After} ->
             Next ! {insert, New, After},
             loop( Data, Next )
        end.

loop_append( New, nonext ) -> New;
loop_append( New, Next ) ->
        Next ! {append, New},
        Next.

loop_foreach( _Fun, nonext ) -> ok;
loop_foreach( Fun, Next ) -> Next ! {foreach, Fun}.


program SleepOneSecond;

{$APPTYPE CONSOLE}

uses SysUtils;

var
  lTimeToSleep: Integer;
begin
  if ParamCount = 0 then
    lTimeToSleep := 1000
  else
    lTimeToSleep := StrToInt(ParamStr(1));
  WriteLn('Sleeping...');
  Sleep(lTimeToSleep); // milliseconds
  WriteLn('Awake!');
end.


begin_instuct(sleepTime);
    ask_human()_first()_msg(Enter number of seconds to sleep: )_var(sleepSecs)_me();
    set_decision(asynchronous)_me();
        me_msg(Sleeping...);
        me_sleep[sleepSecs]_unit(secs);
        me_msg(Awake!);
    reset_decision()_me();
end_instruct(sleepTime);

exec_instruct(sleepTime)_me();


        START    ;Demonstrate the SLEEP function

        RECORD SLEEPING
,       A8, "Sleeping"

        RECORD WAKING
,       A6,"Awake"

        PROC
        XCALL FLAGS (0007000000,1)          ;Suppress STOP message

        OPEN(8,O,'TT:')
        WRITES(8,SLEEPING)
        SLEEP 30   ; Sleep for 30 seconds
        WRITES(8,WAKING)

        END


(() => {
    'use strict';

    // isSmith :: Int -> Bool
    const isSmith = n => {
        const pfs = primeFactors(n);
        return (1 < pfs.length || n !== pfs[0]) && (
            sumDigits(n) === pfs.reduce(
                (a, x) => a + sumDigits(x),
                0
            )
        );
    };

    // TEST -----------------------------------------------

    // main :: IO ()
    const main = () => {

        // lowSmiths :: [Int]
        const lowSmiths = enumFromTo(2)(9999)
            .filter(isSmith);

        // lowSmithCount :: Int
        const lowSmithCount = lowSmiths.length;
        return [
            "Count of Smith Numbers below 10k:",
            show(lowSmithCount),
            "\nFirst 15 Smith Numbers:",
            unwords(take(15)(lowSmiths)),
            "\nLast 12 Smith Numbers below 10000:",
            unwords(drop(lowSmithCount - 12)(lowSmiths))
        ].join('\n');
    };

    // SMITH ----------------------------------------------

    // primeFactors :: Int -> [Int]
    const primeFactors = x => {
        const go = n => {
            const fs = take(1)(
                dropWhile(x => 0 != n % x)(
                    enumFromTo(2)(
                        floor(sqrt(n))
                    )
                )
            );
            return 0 === fs.length ? [n] : fs.concat(
                go(floor(n / fs[0]))
            );
        };
        return go(x);
    };

    // sumDigits :: Int -> Int
    const sumDigits = n =>
        unfoldl(
            x => 0 === x ? (
                Nothing()
            ) : Just(quotRem(x)(10))
        )(n).reduce((a, x) => a + x, 0);

    // GENERIC --------------------------------------------

    // Nothing :: Maybe a
    const Nothing = () => ({
        type: 'Maybe',
        Nothing: true,
    });

    // Just :: a -> Maybe a
    const Just = x => ({
        type: 'Maybe',
        Nothing: false,
        Just: x
    });

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = a => b => ({
        type: 'Tuple',
        '0': a,
        '1': b,
        length: 2
    });

    // drop :: Int -> [a] -> [a]
    // drop :: Int -> String -> String
    const drop = n => xs =>
        xs.slice(n)

    // dropWhile :: (a -> Bool) -> [a] -> [a]
    // dropWhile :: (Char -> Bool) -> String -> String
    const dropWhile = p => xs => {
        const lng = xs.length;
        return 0 < lng ? xs.slice(
            until(i => i === lng || !p(xs[i]))(
                i => 1 + i
            )(0)
        ) : [];
    };

    // enumFromTo :: Int -> Int -> [Int]
    const enumFromTo = m => n =>
        Array.from({
            length: 1 + n - m
        }, (_, i) => m + i);

    // floor :: Num -> Int
    const floor = Math.floor;

    // quotRem :: Int -> Int -> (Int, Int)
    const quotRem = m => n =>
        Tuple(Math.floor(m / n))(
            m % n
        );

    // show :: a -> String
    const show = x => JSON.stringify(x, null, 2);

    // sqrt :: Num -> Num
    const sqrt = n =>
        (0 <= n) ? Math.sqrt(n) : undefined;

    // sum :: [Num] -> Num
    const sum = xs => xs.reduce((a, x) => a + x, 0);

    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n => xs =>
        'GeneratorFunction' !== xs.constructor.constructor.name ? (
            xs.slice(0, n)
        ) : [].concat.apply([], Array.from({
            length: n
        }, () => {
            const x = xs.next();
            return x.done ? [] : [x.value];
        }));

    // unfoldl :: (b -> Maybe (b, a)) -> b -> [a]
    const unfoldl = f => v => {
        let
            xr = [v, v],
            xs = [];
        while (true) {
            const mb = f(xr[0]);
            if (mb.Nothing) {
                return xs
            } else {
                xr = mb.Just;
                xs = [xr[1]].concat(xs);
            }
        }
    };

    // until :: (a -> Bool) -> (a -> a) -> a -> a
    const until = p => f => x => {
        let v = x;
        while (!p(v)) v = f(v);
        return v;
    };

    // unwords :: [String] -> String
    const unwords = xs => xs.join(' ');

    return main();
})();