!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Tue May 21 13:15:59
!
!a=./f && make $a && $a < unixdict.txt
!gfortran -std=f2003 -Wall -ffree-form f.f03 -o f
!    1    2    3    4    5    6    7    8    9   10   12   18   20   21   24   27   30   36   40   42 1002
!
!Compilation finished at Tue May 21 13:15:59

program Harshad
  integer :: i, h = 0
  do i=1, 20
    call nextHarshad(h)
    write(6, '(i5)', advance='no') h
  enddo
  h = 1000
  call nextHarshad(h)
  write(6, '(i5)') h

contains

  subroutine nextHarshad(h) ! alter input integer h to be the next greater Harshad number.
    integer, intent(inout) :: h
    h = h+1 ! bigger
    do while (.not. isHarshad(h))
      h = h+1
    end do
  end subroutine nextHarshad

  logical function isHarshad(a)
    integer, intent(in) :: a
    integer :: mutable, digit_sum
    isHarshad = .false.
    if (a .lt. 1) return ! false if a < 1
    mutable = a
    digit_sum = 0
    do while (mutable /= 0)
      digit_sum = digit_sum + mod(mutable, 10)
      mutable = mutable / 10
    end do
    isHarshad = 0 .eq. mod(a, digit_sum)
  end function isHarshad

end program Harshad


var keys = ['a', 'b', 'c'];
var values = [1, 2, 3];
var map = {};
for(var i = 0; i < keys.length; i += 1) {
  map[ keys[i] ] = values[i];
}


# hash(keys) creates a JSON object with the given keys as keys
# and values taken from the input array in turn.
# "keys" must be an array of strings.
# The input array may be of any length and have values of any type,
# but only the first (keys|length) values will be used;
# the input will in effect be padded with nulls if required.
def hash(keys):
  . as $values
  | reduce range(0; keys|length) as $i
      ( {}; . + { (keys[$i]) : $values[$i] });

[1,2,3] | hash( ["a","b","c"] )


(() => {
    'use strict';

    // hashJoin :: [Dict] -> [Dict] -> String -> [Dict]
    let hashJoin = (tblA, tblB, strJoin) => {

        let [jA, jB] = strJoin.split('='),
            M = tblB.reduce((a, x) => {
                let id = x[jB];
                return (
                    a[id] ? a[id].push(x) : a[id] = [x],
                    a
                );
            }, {});

        return tblA.reduce((a, x) => {
            let match = M[x[jA]];
            return match ? (
                a.concat(match.map(row => dictConcat(x, row)))
            ) : a;
        }, []);
    },

    // dictConcat :: Dict -> Dict -> Dict
    dictConcat = (dctA, dctB) => {
        let ok = Object.keys;
        return ok(dctB).reduce(
            (a, k) => (a['B_' + k] = dctB[k]) && a,
            ok(dctA).reduce(
                (a, k) => (a['A_' + k] = dctA[k]) && a, {}
            )
        );
    };

    // TEST
    let lstA = [
        { age: 27, name: 'Jonah' },
        { age: 18, name: 'Alan' },
        { age: 28, name: 'Glory' },
        { age: 18, name: 'Popeye' },
        { age: 28, name: 'Alan' }
    ],
    lstB = [
        { character: 'Jonah', nemesis: 'Whales' },
        { character: 'Jonah', nemesis: 'Spiders' },
        { character: 'Alan', nemesis: 'Ghosts' },
        { character:'Alan', nemesis: 'Zombies' },
        { character: 'Glory', nemesis: 'Buffy' },
        { character: 'Bob', nemesis: 'foo' }
    ];

    return hashJoin(lstA, lstB, 'name=character');

})();


Start:=A_TickCount
counter=0
SetTimer, timer, 500
return

timer:
Send % ++Counter "`n"
return

^c::
SetTimer, timer, off
SetFormat, float, 0.3
Send, % "Task took " (A_TickCount-Start)/1000 " Seconds"
ExitApp
return


' Handle signal
SUB Finished
    SIGNAL SIG_DFL, SIGINT    : ' Restore SIGINT to default
    PRINT "Running for", TIMER / 1000.0, "seconds" FORMAT "%s %f %s\n"
    STOP SIGINT               : ' Send another terminating SIGINT
ENDSUB

SIGNAL Finished, SIGINT
iter = 1
WHILE TRUE
    SLEEP 500
    PRINT iter
    iter = iter + 1
WEND


      REM!Exefile C:\bbcsigint.exe,encrypt,console
      INSTALL @lib$+"CALLBACK"
      CTRL_C_EVENT = 0

      SYS "GetStdHandle", -10 TO @hfile%(1)
      SYS "GetStdHandle", -11 TO @hfile%(2)
      *INPUT 13
      *OUTPUT 14
      ON ERROR PRINT REPORT$ : QUIT ERR

      CtrlC% = FALSE
      handler% = FN_callback(FNsigint(), 1)
      SYS FN_syscalls("SetConsoleCtrlHandler"), handler%, 1 TO !FN_systo(res%)
      IF res%=0 PRINT "Could not set SIGINT handler" : QUIT 1

      PRINT "Press Ctrl+C to test...."
      TIME = 0
      Time% = 50
      REPEAT
        WAIT 1
        IF TIME > Time% THEN
          PRINT Time%
          Time% += 50
        ENDIF
      UNTIL CtrlC%
      PRINT "Ctrl+C was pressed after "; TIME/100 " seconds."
      QUIT

      DEF FNsigint(T%)
      CASE T% OF
        WHEN CTRL_C_EVENT: CtrlC% = TRUE : = 1
      ENDCASE
      = 0


#include <stdio.h>
#include <stdlib.h>	// for exit()
#include <signal.h>
#include <time.h>	// for clock()
#include <unistd.h>	// for POSIX usleep()

volatile sig_atomic_t gotint = 0;

void handleSigint() {
    /*
     * Signal safety: It is not safe to call clock(), printf(),
     * or exit() inside a signal handler. Instead, we set a flag.
     */
    gotint = 1;
}

int main() {
    clock_t startTime = clock();
    signal(SIGINT, handleSigint);
    int i=0;
    for (;;) {
        if (gotint)
            break;
        usleep(500000);
        if (gotint)
            break;
	printf("%d\n", ++i);
    }
    clock_t endTime = clock();
    double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
    printf("Program has run for %5.3f seconds\n", td);
    return 0;
}


' FB 1.05.0 Win64

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

Function isHarshad(n As Integer) As Boolean
  Return n Mod sumDigits(n) = 0
End Function

Print "The first 20 Harshad or Niven numbers are :"
Dim count As Integer = 0
Dim i As Integer = 1

Do
  If isHarshad(i) Then
    Print i; " ";
    Count += 1
    If count = 20 Then Exit Do
  End If
  i += 1
Loop

Print : Print
Print "The first such number above 1000 is :"
i = 1001

Do
  If isHarshad(i) Then
    Print i; " "
    Exit Do
  End If
  i += 1
Loop

Print
Print "Press any key to quit"
Sleep


isHarshad[n] := n mod sum[integerDigits[n]] == 0

c = 0
i = 1
while c<20
{
   if isHarshad[i]
   {
      c = c + 1
      println[i]
   }
   i = i + 1
}

println[]
i = 1000

do
   i = i + 1
while ! isHarshad[i]

println[i]


   a: `zero `one `two  / symbols
   b: 0 1 2

   d:. a,'b  / create the dictionary
.((`zero;0;)
  (`one;1;)
  (`two;2;))

   d[`one]
1


// version 1.1.0

fun main(args: Array<String>) {
    val names = arrayOf("Jimmy", "Bill", "Barack", "Donald")
    val ages  = arrayOf(92, 70, 55, 70)
    val hash  = mapOf(*names.zip(ages).toTypedArray())
    hash.forEach { println("${it.key.padEnd(6)} aged ${it.value}") }
}


: >table  2 compress -1 transpose ;
['one 'two 'three 'four] [1 2 3 4] >table


# hashJoin(table1; key1; table2; key2) expects the two tables to be
# arrays, either of JSON objects, or of arrays.

# In the first case, that is, if the table's rows are represented as
# objects, then key1 should be the key of the join column of table1,
# and similarly for key2; if the join columns have different names,
# then they will both be included in the resultant objects.

# In the second case, that is, if the rows are arrays, then the
# 0-based indices of the join columns should be specified, and the
# rows are simply pasted together, resulting in duplication of the
# join columns.
#
def hashJoin(table1; key1; table2; key2):
  # collision-free hash function:
  def h:
    if type == "object" then with_entries(.value = (.value|h)) | tostring
    elif type == "array" then map(h)|tostring
    else (type[0:1]+tostring)
    end;

  # hash phase:
  reduce table1[] as $row
    ({};
     ($row[key1]|h) as $key
     | . + { ($key): (.[$key] + [$row]) } )
  | . as $hash
  # join phase
  | reduce table2[] as $row
      ([];
       ($row[key2]|h) as $key
       | if $hash|has($key) then
           reduce $hash[$key][] as $r (.; . +  [ $row + $r ] )
  	 else . end)
;


using DataFrames

A = DataFrame(Age = [27, 18, 28, 18, 28], Name = ["Jonah", "Alan", "Glory", "Popeye", "Alan"])
B = DataFrame(Name = ["Jonah", "Jonah", "Alan", "Alan", "Glory"],
    Nemesis = ["Whales", "Spiders", "Ghosts", "Zombies", "Buffy"])
AB = join(A, B, on = :Name)

@show A B AB


data class A(val age: Int, val name: String)

data class B(val character: String, val nemesis: String)

data class C(val rowA: A, val rowB: B)

fun hashJoin(tableA: List<A>, tableB: List<B>): List<C> {
    val mm = tableB.groupBy { it.character }
    val tableC = mutableListOf<C>()
    for (a in tableA) {
        val value = mm[a.name] ?: continue
        for (b in value) tableC.add(C(a, b))
    }
    return tableC.toList()
}

fun main(args: Array<String>) {
    val tableA = listOf(
        A(27, "Jonah"),
        A(18, "Alan"),
        A(28, "Glory"),
        A(18, "Popeye"),
        A(28, "Alan")
    )
    val tableB = listOf(
        B("Jonah", "Whales"),
        B("Jonah", "Spiders"),
        B("Alan", "Ghosts"),
        B("Alan", "Zombies"),
        B("Glory", "Buffy")
    )
    val tableC = hashJoin(tableA, tableB)
    println("A.Age A.Name B.Character B.Nemesis")
    println("----- ------ ----------- ---------")
    for (c in tableC) {
        print("${c.rowA.age}    ${c.rowA.name.padEnd(6)} ")
        println("${c.rowB.character.padEnd(6)}      ${c.rowB.nemesis}")
    }
}


using System; //DateTime, Console, Environment classes
class Program
{
    static DateTime start;
    static void Main(string[] args)
    {
        start = DateTime.Now;
        //Add event handler for Ctrl+C command
        Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
        int counter = 0;
        while (true)
        {
            Console.WriteLine(++counter);
            System.Threading.Thread.Sleep(500);
        }
    }
    static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
    {
        var end = DateTime.Now;
        Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
        Environment.Exit(0);
    }
}


#include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>

volatile sig_atomic_t gotint = 0;

void handler(int signum) {
	// Set a flag for handling the signal, as other methods like printf are not safe here
	gotint = 1;
}

int main() {
	using namespace std;

	signal(SIGINT, handler);

	int i = 0;
	clock_t startTime = clock();
	while (true) {
		if (gotint) break;
		std::this_thread::sleep_for(std::chrono::milliseconds(500));
		if (gotint) break;
		cout << ++i << endl;
	}
	clock_t endTime = clock();

	double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
	cout << "Program has run for " << dt << " seconds" << endl;

	return 0;
}


(require 'clojure.repl)

(def start (System/nanoTime))

(defn shutdown [_]
  (println "Received INT after"
           (/ (- (System/nanoTime) start) 1e9)
           "seconds.")
  (System/exit 0))

(clojure.repl/set-break-handler! shutdown)

(doseq [i (range)]
  (prn i)
  (Thread/sleep 500))


Public Sub Main()
Dim siCount, siLoop, siTotal, siCounter As Short
Dim sNo, sTemp As String
Dim sHold, sNiven As New String[]

For siCount = 1 To 1500
  sNo = Str(siCount)
  For siLoop = 1 To Len(sNo)
    sHold.Add(Mid(sNo, siLoop, 1))
  Next
  For Each sTemp In sHold
    siTotal += Val(sTemp)
  Next
  If siCount Mod siTotal = 0 Then
    Inc siCounter
    If siCounter < 21 Or siCount > 1000 Then
      sNiven.Add(Str(siCount))
      If siCount > 1000 Then Break
    Endif
  Endif
  siTotal = 0
  sHold.Clear
Next

Print "First twenty Harshad numbers and the first Harshad number greater than 1000"
Print sNiven.Join(", ")

End


local(
	array1	= array('a', 'b', 'c'),
	array2	= array(1, 2, 3),
	hash	= map
)

loop(#array1 -> size) => {
	#hash -> insert(#array1 -> get(loop_count) = #array2 -> get(loop_count))
}

#hash


(let* ((keys (list 'foo 'bar 'baz))
       (vals (list '"foo data" '"bar data" '"baz data"))
       (tuples (: lists zipwith
                 (lambda (a b) (tuple a b)) keys vals))
       (my-dict (: dict from_list tuples)))
  (: io format '"fetched data: ~p~n" (list (: dict fetch 'baz my-dict))))


keys = ["a","b","c"]
values = [1,2,3]

props = [:]
cnt = keys.count
repeat with i = 1 to cnt
  props[keys[i]] = values[i]
end repeat

put props
-- ["a": 1, "b": 2, "c": 3]


put "a,b,c" into list1
put 10,20,30 into list2
split list1 using comma
split list2 using comma
repeat with i=1 to the number of elements of list1
    put list2[i] into list3[list1[i]]
end repeat
combine list3 using comma and colon
put list3

-- ouput
-- a:10,b:20,c:30


function(keys,values)
  local t = {}
  for i=1, #keys do
    t[keys[i]] = values[i]
  end
end


local function recA(age, name) return { Age=age, Name=name } end
local tabA = { recA(27,"Jonah"), recA(18,"Alan"), recA(28,"Glory"), recA(18,"Popeye"), recA(28,"Alan") }

local function recB(character, nemesis) return { Character=character, Nemesis=nemesis } end
local tabB = { recB("Jonah","Whales"), recB("Jonah","Spiders"), recB("Alan","Ghosts"), recB("Alan","Zombies"), recB("Glory","Buffy") }

local function hashjoin(taba, cola, tabb, colb)
  local hash, join = {}, {}
  for _,rowa in pairs(taba) do
    if (not hash[rowa[cola]]) then hash[rowa[cola]] = {} end
    table.insert(hash[rowa[cola]], rowa)
  end
  for _,rowb in pairs(tabb) do
    for _,rowa in pairs(hash[rowb[colb]]) do
      join[#join+1] = { A=rowa, B=rowb }
    end
  end
  return join
end

for _,row in pairs(hashjoin(tabA, "Name", tabB, "Character")) do
  print(row.A.Age, row.A.Name, row.B.Character, row.B.Nemesis)
end


(defun hash (column table)
  (lists:foldl
    (lambda (x acc)
      (orddict:append (proplists:get_value column x) x acc))
    '()
    table))

(defun get-hash (col hash-table)
  (proplists:get_value
     (proplists:get_value col r)
     hashed))

(defun merge (row-1 row-2)
  (orddict:merge
    (lambda (k v1 v2) v2)
    (lists:sort row-1)
    (lists:sort row-2)))

(defun hash-join (table-1 col-1 table-2 col-2)
  (let ((hashed (hash col-1 table-1)))
    (lc ((<- r table-2))
        (lc ((<- s (get-hash col-2 hashed)))
            (merge r s)))))


       identification division.
       program-id. signals.
       data division.
       working-storage section.
       01 signal-flag  pic 9 external.
          88 signalled value 1.
       01 half-seconds usage binary-long.
       01 start-time   usage binary-c-long.
       01 end-time     usage binary-c-long.
       01 handler      usage program-pointer.
       01 SIGINT       constant as 2.

       procedure division.
       call "gettimeofday" using start-time null
       set handler to entry "handle-sigint"
       call "signal" using by value SIGINT by value handler

       perform until exit
           if signalled then exit perform end-if
           call "CBL_OC_NANOSLEEP" using 500000000
           if signalled then exit perform end-if
           add 1 to half-seconds
           display half-seconds
       end-perform

       call "gettimeofday" using end-time null
       subtract start-time from end-time
       display "Program ran for " end-time " seconds"
       goback.
       end program signals.

       identification division.
       program-id. handle-sigint.
       data division.
       working-storage section.
       01 signal-flag  pic 9 external.

       linkage section.
       01 the-signal   usage binary-long.

       procedure division using by value the-signal returning omitted.
       move 1 to signal-flag
       goback.
       end program handle-sigint.


(ql:quickload :cffi)

(defconstant +SIGINT+ 2)

(defmacro set-signal-handler (signo &body body)
  (let ((handler (gensym "HANDLER")))
    `(progn
       (cffi:defcallback ,handler :void ((signo :int))
         (declare (ignore signo))
         ,@body)
       (cffi:foreign-funcall "signal" :int ,signo :pointer (cffi:callback ,handler)))))

(defvar *initial* (get-internal-real-time))

(set-signal-handler +SIGINT+
  (format t "Ran for ~a seconds~&" (/ (- (get-internal-real-time) *initial*) internal-time-units-per-second))
  (quit))

(let ((i 0))
  (loop do
    (format t "~a~&" (incf i))
    (sleep 0.5)))


export Executable

run() = println("Hello world!")


package main

import "fmt"

type is func() int

func newSum() is {
    var ms is
    ms = func() int {
        ms = newSum()
        return ms()
    }
    var msd, d int
    return func() int {
        if d < 9 {
            d++
        } else {
            d = 0
            msd = ms()
        }
        return msd + d
    }
}

func newHarshard() is {
    i := 0
    sum := newSum()
    return func() int {
        for i++; i%sum() != 0; i++ {
        }
        return i
    }
}

func main() {
    h := newHarshard()
    fmt.Print(h())
    for i := 1; i < 20; i++ {
        fmt.Print(" ", h())
    }
    fmt.Println()
    h = newHarshard()
    n := h()
    for ; n <= 1000; n = h() {
    }
    fmt.Println(n)
}


Module CheckAll {
      Module CheckVectorType {
            Dim Keys$(4), Values(4)
            Keys$(0):= "one","two","three","four"
            Values(0):=1,2,3,4
            Inventory Dict
            For i=0 to 3 {
                  Append Dict, Keys$(i):=Values(i)
            }
            Print Dict("one")+Dict("four")=Dict("two")+Dict("three")  ' true
      }
      Module CheckVectorType1 {
            Dim Keys$(4), Values$(4)
            Keys$(0):= "one","two","three","four"
            Values$(0):="*","**","***","****"
            Inventory Dict
            For i=0 to 3 {
                  Append Dict, Keys$(i):=Values$(i)
            }
            Print Dict$("one")+Dict$("four")=Dict$("two")+Dict$("three")  ' true
      }
      CheckVectorType
      CheckVectorType1
}
CheckAll


Module HashJoin {
      \\ normally we define variables when we put values to names
      \\ so we can remove these two lines
      Def Name$, Nemesis$
      Def Long m, mc, items_size, A

      \\ Lets make a container which use keys with hash function
      Inventory A
      \\ A now is a pointer to an Inventory, with Len(A)=0
      \\ Print Type$(A)="Inventory"

      \\ empty stack. We use current stack to place data
      Flush
      \Input B
      data "Jonah", "Whales"
      data "Jonah", "Spiders"
      data "Alan", "Ghosts"
      data "Alan", "Zombies"
      data "Glory", "Buffy"
      \\ Keys are unique, This is the HASH PHASE
      While not empty {
            Read Name$, Nemesis$
            If Exist(A, Name$) Then {
                  m=Eval(A)  ' get a pointer to array
                  Stack m {Data Nemesis$}
            } Else Append A, Name$:=Stack:=Nemesis$  ' a stack object with one item
      }
      \\ Input A, this is the Long Table
      data 27, "Jonah"
      data 18, "Alan"
      data 28, "Glory"
      data 18, "Popeye"
      data 28, "Alan"

      \\ This is the JOIN PHASE

      items_size=stack.size/2
      \\ using items_size we can append data (using data) to stack
      \\ $(0) is the default handler for columns.
      \\ Letters justify to left, numbers to right.
      \\ Letters can use more columns, and maybe wrap to more lines.

      Print $(0), "Output during join"
      Print "A.Age", "A.Name","B.Character", "B.Nemesis"
      While items_size>0 {
            Read Age, Name$
            If exist(A, Name$) Then {
                  m=Eval(A)   ' extract a pointer, this is for a stack object
                  mc=Each(m)  ' make an iterator
                  While mc {
                        \\ we use $(1) for left justify numbers too
                        \\ normal StackItem$(stackobject) return top only
                        \\ we have to use StackItem$(stackobject, 3) to get 3rd
                        \\ or StackItem(stackobject, 3) if it is numeric.
                        \\ but here mc is iterator, and place the cursor value to it
                       Print $(1), Age, Name$,Name$, StackItem$(mc)
                        \\ so now we place at the end of current stack the same output
                       Data Age, Name$,Name$, StackItem$(mc)
                  }
            }
            items_size--
      }
      \\ split rem line after : to use second way
      rem : goto secondway
      Print $(0), "Output after join"
      Print "A.Age", "A.Name","B.Character", "B.Nemesis"
      While not Empty {
            Print $(1), Number, Letter$, Letter$, Letter$
      }
      Exit
secondway:
      Print $(0), "Output after join using format$()"
      Print Format$("{0:5} {1:10} {2:10} {3:20}","A.Age", "A.Name","B.Character", "B.Nemesis")
      While not Empty {
            Print format$("{0::5} {1:10} {2:10} {3:20}", Number, Letter$, Letter$, Letter$)
      }
}
HashJoin


import strformat, tables

type
  Data1 = tuple[value: int; key: string]
  Data2 = tuple[key: string; value: string]

proc `$`(d: Data1 | Data2): string = &"({d[0]}, {d[1]})"

iterator hashJoin(table1: openArray[Data1]; table2: openArray[Data2]): tuple[a: Data1; b: Data2] =
  # Hash phase.
  var h: Table[string, seq[Data1]]
  for s in table1:
    h.mgetOrPut(s.key, @[]).add(s)
  # Join phase.
  for r in table2:
    for s in h[r.key]:
      yield (s, r)

let table1 = [(27, "Jonah"),
              (18, "Alan"),
              (28, "Glory"),
              (18, "Popeye"),
              (28, "Alan")]

let table2 = [("Jonah", "Whales"),
              ("Jonah", "Spiders"),
              ("Alan", "Ghosts"),
              ("Alan", "Zombies"),
              ("Glory", "Buffy")]

for row in hashJoin(table1, table2):
  echo row.a, " ", row.b


MODULE HashJoin;
IMPORT
  ADT:Dictionary,
  ADT:LinkedList,
  NPCT:Tools,
  Object,
  Object:Boxed,
  Out;
TYPE
  (* Some Aliases *)
  Age= Boxed.LongInt;
  Name= STRING;
  Nemesis= STRING;

  (* Generic Tuple *)
  Tuple(E1: Object.Object; E2: Object.Object) = POINTER TO TupleDesc(E1,E2);
  TupleDesc(E1: Object.Object; E2: Object.Object) = RECORD
    (Object.ObjectDesc)
    _1: E1;
    _2: E2;
  END;

  (* Relations *)
  RelationA = ARRAY 5 OF Tuple(Age,Name);
  RelationB = ARRAY 5 OF Tuple(Name,Nemesis);

VAR
  tableA: RelationA;
  tableB: RelationB;
  dict: Dictionary.Dictionary(Name,LinkedList.LinkedList(Age));
  ll: LinkedList.LinkedList(Age);

  PROCEDURE (t: Tuple(E1, E2)) INIT*(e1: E1; e2: E2);
  BEGIN
    t._1 := e1;
    t._2 := e2;
  END INIT;

  PROCEDURE DoHashPhase(t: RelationA;VAR dict: Dictionary.Dictionary(Name,LinkedList.LinkedList(Age)));
  VAR
    i: INTEGER;
    ll: LinkedList.LinkedList(Age);
  BEGIN
    i := 0;
    WHILE (i < LEN(t)) & (t[i] # NIL) DO
      IF (dict.HasKey(t[i]._2)) THEN
        ll := dict.Get(t[i]._2);
      ELSE
        ll := NEW(LinkedList.LinkedList(Age));
        dict.Set(t[i]._2,ll)
      END;
      ll.Append(t[i]._1);
      INC(i)
    END
  END DoHashPhase;

  PROCEDURE DoJoinPhase(t: RelationB; dict: Dictionary.Dictionary(Name,LinkedList.LinkedList(Age)));
  VAR
    i: INTEGER;
    age: Age;
    iterll: LinkedList.Iterator(Age);
  BEGIN
    FOR i := 0 TO LEN(t) - 1 DO
    ll := dict.Get(t[i]._1);
    iterll := ll.GetIterator(NIL);
    WHILE iterll.HasNext() DO
      age := iterll.Next();
      Out.LongInt(age.value,4);
      Out.Object(Tools.AdjustRight(t[i]._1,10));
      Out.Object(Tools.AdjustRight(t[i]._2,10));Out.Ln
    END
  END
  END DoJoinPhase;

BEGIN
  (* tableA initialization *)
  tableA[0] := NEW(Tuple(Age,Name),NEW(Age,27),"Jonah");
  tableA[1] := NEW(Tuple(Age,Name),NEW(Age,18),"Alan");
  tableA[2] := NEW(Tuple(Age,Name),NEW(Age,28),"Glory");
  tableA[3] := NEW(Tuple(Age,Name),NEW(Age,18),"Popeye");
  tableA[4] := NEW(Tuple(Age,Name),NEW(Age,28),"Alan");

  (* tableB initialization *)
  tableB[0] := NEW(Tuple(Name,Nemesis),"Jonah","Whales");
  tableB[1] := NEW(Tuple(Name,Nemesis),"Jonah","Spiders");
  tableB[2] := NEW(Tuple(Name,Nemesis),"Alan","Ghost");
  tableB[3] := NEW(Tuple(Name,Nemesis),"Alan","Zombies");
  tableB[4] := NEW(Tuple(Name,Nemesis),"Glory","Buffy");

  dict := NEW(Dictionary.Dictionary(Name,LinkedList.LinkedList(Age)));

  DoHashPhase(tableA,dict);
  DoJoinPhase(tableB,dict);
END HashJoin.


start = Time.utc
ch = Channel(Int32 | Symbol).new

spawn do
  i = 0
  loop do
    sleep 1
    ch.send(i += 1)
  end
end

Signal::INT.trap do
  Signal::INT.reset
  ch.send(:kill)
end

loop do
  x = ch.receive
  break if x == :kill
  puts x
end

elapsed = Time.utc - start
puts "Program has run for %5.3f seconds." % elapsed.total_seconds


import core.stdc.signal;
import core.thread;
import std.concurrency;
import std.datetime.stopwatch;
import std.stdio;

__gshared int gotint = 0;
extern(C) void handleSigint(int sig) nothrow @nogc @system {
    /*
     * Signal safety: It is not safe to call clock(), printf(),
     * or exit() inside a signal handler. Instead, we set a flag.
     */
    gotint = 1;
}

void main() {
    auto sw = StopWatch(AutoStart.yes);
    signal(SIGINT, &handleSigint);
    for (int i=0; !gotint;) {
        Thread.sleep(500_000.usecs);
        if (gotint) {
            break;
        }
        writeln(++i);
    }
    sw.stop();
    auto td = sw.peek();
    writeln("Program has run for ", td);
}


#! /usr/bin/env escript

main([]) ->
    erlang:unregister(erl_signal_server),
    erlang:register(erl_signal_server, self()),
    Start = seconds(),
    os:set_signal(sigquit, handle),
    Pid = spawn(fun() -> output_loop(1) end),
    receive
        {notify, sigquit} ->
            erlang:exit(Pid, normal),
            Seconds = seconds() - Start,
            io:format("Program has run for ~b seconds~n", [Seconds])
    end.

seconds() ->
    calendar:datetime_to_gregorian_seconds({date(),time()}).

output_loop(N) ->
    io:format("~b~n",[N]),
    timer:sleep(500),
    output_loop(N + 1).


module HelloWorld where
main _ = println "Hello world!"


class HarshadNiven{ public static boolean find(int x)
   {
     int sum = 0,temp,var;
      var = x;
     while(x>0)
       {
         temp = x%10;
         sum = sum + temp;
         x = x/10;
       }
     if(var%sum==0) temp = 1;
     else temp = 0;
    return temp;
   }
 public static void main(String[] args)
  {
    int t,i;
     t = 0;
     for(i=1;t<20;i++)
      {
        if(find(i))
           {
             print(i + " ");
             t++;
           }
      }
     int x = 0;
     int y = 1000;
     while(x!=1)
      {
        if(find(y)) x = 1;
         y++;
      }
    println();
    println(y+1);
  }
}


Map[(Hash[Part[#, 1]] = Part[#, 2]) &,
 Transpose[{{1, 2, 3}, {"one", "two", "three"}}]]

?? Hash
->Hash[1]=one
->Hash[2]=two
->Hash[3]=three


function s = StructFromArrays(allKeys, allVals)
% allKeys must be cell array of strings of valid field-names
% allVals can be cell array or array of numbers
% Assumes arrays are same size and valid types
    s = struct;
    if iscell(allVals)
        for k = 1:length(allKeys)
            s.(allKeys{k}) = allVals{k};
        end
    else
        for k = 1:length(allKeys)
            s.(allKeys{k}) = allVals(k);
        end
    end
end


keys = ["foo", "bar", "val"]
values = ["little", "miss", "muffet"]

d = {}
for i in range(keys.len-1)
    d[keys[i]] = values[i]
end for

print d


/**
 <doc>
Hash from two arrays, in Neko
</doc>
**/

var sprintf = $loader.loadprim("[email protected]", 2)

var array_keys = $array("one",2,"three",4,"five")
var array_vals = $array("six",7,"eight",9,"zero")
var elements = $asize(array_keys)

var table = $hnew(elements)

var step = elements
while (step -= 1) >= 0 $hadd(table, $hkey(array_keys[step]), array_vals[step])

/*
 $hiter accepts a hashtable and a function that accepts two args, key, val
*/
var show = function(k, v) $print("Hashed key: ", sprintf("%10d", k), " Value: ", v, "\n")
$hiter(table, show)


let hash_join table1 f1 table2 f2 =
  let h = Hashtbl.create 42 in
  (* hash phase *)
  List.iter (fun s ->
    Hashtbl.add h (f1 s) s) table1;
  (* join phase *)
  List.concat (List.map (fun r ->
    List.map (fun s -> s, r) (Hashtbl.find_all h (f2 r))) table2)


use Data::Dumper qw(Dumper);

sub hashJoin {
    my ($table1, $index1, $table2, $index2) = @_;
    my %h;
    # hash phase
    foreach my $s (@$table1) {
	push @{ $h{$s->[$index1]} }, $s;
    }
    # join phase
    map { my $r = $_;
	  map [$_, $r], @{ $h{$r->[$index2]} }
    } @$table2;
}

@table1 = ([27, "Jonah"],
           [18, "Alan"],
           [28, "Glory"],
           [18, "Popeye"],
           [28, "Alan"]);
@table2 = (["Jonah", "Whales"],
           ["Jonah", "Spiders"],
           ["Alan", "Ghosts"],
           ["Alan", "Zombies"],
           ["Glory", "Buffy"]);

$Data::Dumper::Indent = 0;
foreach my $row (hashJoin(\@table1, 1, \@table2, 0)) {
    print Dumper($row), "\n";
}


open System

let rec loop n = Console.WriteLine( n:int )
                 Threading.Thread.Sleep( 500 )
                 loop (n + 1)

let main() =
   let start = DateTime.Now
   Console.CancelKeyPress.Add(
      fun _ -> let span = DateTime.Now - start
               printfn "Program has run for %.0f seconds" span.TotalSeconds
             )
   loop 1

main()


-28 constant SIGINT

: numbers ( n -- n' )
  begin dup . cr  1+  500 ms again ;

: main
  utime
  0 begin
    ['] numbers catch
    SIGINT =
  until drop
  utime d- dnegate
  <# # # # # # # [char] . hold #s #> type ."  seconds" ;

main bye


Dim Shared As Double start
start = Timer

Dim As Integer n = 1
Dim As String s
Do
    Print n
    s = Inkey
    If s = Chr(255) + "k" Then
        Dim As Double elapsed = Timer- start + n * 0.5
        Print Using "Program has run for & seconds."; elapsed
        End
    Else
        Sleep 500, 1
        n += 1
    End If
Loop


hTimer As Timer
fTime As Float

Public Sub Application_Signal(x As Integer)

Print "Program stopped after " & fTime & " seconds"
Quit

End

Public Sub Main()

hTimer = New Timer As "IntTimer"

Print "Press [Ctrl] + " & Chr(92) & " to stop"

Signal[Signal.SIGQUIT].Catch

With hTimer
  .Delay = 500
  .Start
End With

End

Public Sub IntTimer_Timer()

Print Rand(0, 100)
fTime += 0.5

End


import Data.Char (digitToInt)

harshads :: [Int]
harshads =
  let digsum = sum . map digitToInt . show
  in filter ((0 ==) . (mod <*> digsum)) [1 ..]

main :: IO ()
main = mapM_ print [take 20 harshads, [(head . filter (> 1000)) harshads]]


procedure main(A)
    limit := integer(A[1]) | 20
    every writes(niven(seq())\limit," ")
    writes("... ")
    write(niven(seq(1001))\1)
end

procedure niven(n)
    n ? {s := 0; while s +:= move(1)}
    if (n%s) = 0 then return n
end


using System;
using System.Console;
using Nemerle.Collections;
using Nemerle.Collections.NCollectionsExtensions;

module AssocArray
{
    Main() : void
    {
        def list1 = ["apples", "oranges", "bananas", "kumquats"];
        def list2 = [13, 34, 12];
        def inventory = Hashtable(ZipLazy(list1, list2));
        foreach (item in inventory)
            WriteLine("{0}:   {1}", item.Key, item.Value);
    }
}


/* NetRexx program ****************************************************
* 04.11.2012 Walter Pachl  derived from REXX
**********************************************************************/
options replace format comments java crossref savelog symbols nobinary
  values='triangle quadrilateral pentagon hexagon heptagon octagon' -
         'nonagon decagon dodecagon'
  keys  ='three four five six seven eight nine ten twelve'
  kcopy=keys
  k=''                                 /* initialize the arrays      */
  v=''
  value='unknown'
  Loop i=1 By 1 While kcopy>''         /* initialize the two arrays  */
    Parse kcopy  ki kcopy;  k[i]=ki
    Parse values vi values; v[i]=vi
    End
  Loop j=1 To i-1
    value[k[j]]=v[j]
    End
  Say 'Enter one of these words:'
  Say ' 'keys
  Parse Ask z
  Say z '->' value[z]


import tables, sequtils

let keys = @['a','b','c']
let values = @[1, 2, 3]

let table = toTable zip(keys, values)


MODULE HashFromArrays;
IMPORT
  ADT:Dictionary,
  Object:Boxed;
TYPE
  Key= STRING;
  Value= Boxed.LongInt;

  PROCEDURE Do;
  VAR
    a: ARRAY 128 OF Key;
    b: ARRAY 128 OF Value;
    hash: Dictionary.Dictionary(Key,Value);
    i: INTEGER;

  BEGIN
    hash := NEW(Dictionary.Dictionary(Key,Value));
    a[0] := "uno";
    a[1] := "dos";
    a[2] := "tres";
    a[3] := "cuatro";
    b[0] := Boxed.ParseLongInt("1");
    b[1] := Boxed.ParseLongInt("2");
    b[2] := Boxed.ParseLongInt("3");
    b[3] := Boxed.ParseLongInt("4");
    i := 0;
    WHILE (i < LEN(a)) & (a[i] # NIL) DO
      hash.Set(a[i],b[i]);
      INC(i)
    END;

  END Do;
BEGIN
  Do;
END HashFromArrays.


with javascript_semantics
constant A = {{27,"Jonah"},
              {18,"Alan"},
              {28,"Glory"},
              {18,"Popeye"},
              {28,"Alan"}},
         B = {{"Jonah","Whales"},
              {"Jonah","Spiders"},
              {"Alan", "Ghosts"},
              {"Alan", "Zombies"},
              {"Glory","Buffy"}},
        jA = 2,
        jB = 1,
        MB = new_dict()
sequence C = {}
for i=1 to length(B) do
    object key = B[i][jB]
    object data = getd(key,MB)
    if data=0 then
        data = {B[i]}
    else
        data = append(data,B[i])
    end if
    putd(key,data,MB)
end for
for i=1 to length(A) do
    object data = getd(A[i][jA],MB)
    if sequence(data) then
        for j=1 to length(data) do
            C = append(C,{A[i],data[j]})
        end for
    end if
end for
destroy_dict(MB)
pp(C,{pp_Nest,1})


<?php
function hashJoin($table1, $index1, $table2, $index2) {
    // hash phase
    foreach ($table1 as $s)
        $h[$s[$index1]][] = $s;
    // join phase
    foreach ($table2 as $r)
    	foreach ($h[$r[$index2]] as $s)
	    $result[] = array($s, $r);
    return $result;
}

$table1 = array(array(27, "Jonah"),
           array(18, "Alan"),
           array(28, "Glory"),
           array(18, "Popeye"),
           array(28, "Alan"));
$table2 = array(array("Jonah", "Whales"),
           array("Jonah", "Spiders"),
           array("Alan", "Ghosts"),
           array("Alan", "Zombies"),
           array("Glory", "Buffy"),
           array("Bob", "foo"));

foreach (hashJoin($table1, 1, $table2, 0) as $row)
    print_r($row);
?>


package main

import (
    "fmt"
    "os"
    "os/signal"
    "time"
)

func main() {
    start := time.Now()
    k := time.Tick(time.Second / 2)
    sc := make(chan os.Signal, 1)
    signal.Notify(sc, os.Interrupt)
    for n := 1; ; {
        // not busy waiting, this blocks until one of the two
        // channel operations is possible
        select {
        case <-k:
            fmt.Println(n)
            n++
        case <-sc:
            fmt.Printf("Ran for %f seconds.\n",
                time.Now().Sub(start).Seconds())
            return
        }
    }
}


import Prelude hiding (catch)
import Control.Exception (catch, throwIO, AsyncException(UserInterrupt))
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Control.Concurrent (threadDelay)

main = do t0 <- getCurrentTime
          catch (loop 0)
                (\e -> if e == UserInterrupt
                         then do t1 <- getCurrentTime
                                 putStrLn ("\nTime: " ++ show (diffUTCTime t1 t0))
                         else throwIO e)

loop i = do print i
            threadDelay 500000 {- µs -}
            loop (i + 1)


seconds = TIME()

DO i = 1, 1E100      ! "forever"
  SYSTEM(WAIT = 500) ! milli seconds
  WRITE(Name) i
ENDDO

SUBROUTINE F2        ! call by either the F2 key, or by a toolbar-F2 click
   seconds = TIME() - seconds
   WRITE(Messagebox, Name) seconds
   ALARM(999)        ! quit immediately
END


global startTime

procedure main()
    startTime := &now
    trap("SIGINT", handler)
    every write(seq()) do delay(500)
end

procedure handler(s)
    stop("\n",&now-startTime," seconds")
end


window 1
print @"Hello world!"

HandleEvents


100 PROGRAM "Harshad.bas"
110 LET I=1:LET CNT=0
120 PRINT "First 20 Harshad numbers are:"
130 DO
140   IF HARSHAD(I) THEN PRINT I;:LET CNT=CNT+1
150   LET I=I+1
160 LOOP UNTIL CNT=20
170 PRINT :PRINT :PRINT "First Harshad number larger than 1000 is";:LET I=1001
180 DO
190   IF HARSHAD(I) THEN PRINT I:EXIT DO
200   LET I=I+1
210 LOOP
220 DEF HARSHAD(NUM)
230   LET TMP=NUM:LET SUM=0
240   DO WHILE TMP>0
250     LET SUM=SUM+MOD(TMP,10)
260     LET TMP=INT(TMP/10)
270   LOOP
280   LET HARSHAD=MOD(NUM,SUM)=0
290 END DEF


Until =: 2 : 'u^:([email protected]:v)^:_'
isHarshad =: 0 = ] |~ [: +/ #.inv  NB. BASE isHarshad N
assert 1 0 -: 10 isHarshad&> 42 38
nextHarshad =: (>: Until (10&isHarshad))@:>:
assert 45 -: nextHarshad 42
assert 3 4 5 -: nextHarshad&> 2 3 4
assert 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 -: (, [email protected]:{:)Until (20 = #) 1
assert 1002 -: nextHarshad 1000

   NB. next Harshad number in base 6.  Input and output are in base 6.
   NB. Verification left to you, gentle programmer.
   nextHarshad_base_6 =: (>: Until (6&isHarshad))@:>:
   ' '-.~":6#.inv nextHarshad_base_6 6b23235
23253


use Structure;

bundle Default {
  class HashOfTwo {
    function : Main(args : System.String[]) ~ Nil {
      keys := ["1", "2", "3"];
      vals := ["a", "b", "c"];
      hash := StringHash->New();
      each(i : vals) {
        hash->Insert(keys[i], vals[i]->As(Base));
      };
    }
  }
}


NSArray *keys = @[@"a", @"b", @"c"];
NSArray *values = @[@1, @2, @3];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];


let keys = [ "foo"; "bar"; "baz" ]
and vals = [ 16384; 32768; 65536 ]
and hash = Hashtbl.create 0;;

List.iter2 (Hashtbl.add hash) keys vals;;


(de A
   (27 . Jonah)
   (18 . Alan)
   (28 . Glory)
   (18 . Popeye)
   (28 . Alan) )

(de B
   (Jonah . Whales)
   (Jonah . Spiders)
   (Alan . Ghosts)
   (Alan . Zombies)
   (Glory . Buffy) )

(for X B
   (let K (cons (char (hash (car X))) (car X))
      (if (idx 'M K T)
         (push (caar @) (cdr X))
         (set (car K) (list (cdr X))) ) ) )

(for X A
   (let? Y (car (idx 'M (cons (char (hash (cdr X))) (cdr X))))
      (for Z (caar Y)
         (println (car X) (cdr X) (cdr Y) Z) ) ) )


\newtoks\tabjoin
\def\quark{\quark}
\def\tabA{27:Jonah,18:Alan,28:Glory,18:Popeye,28:Alan}
\def\tabB{Jonah:Whales,Jonah:Spiders,Alan:Ghosts,Alan:Zombies,Glory:Buffy}
\def\mergejoin{\tabjoin{}\expandafter\mergejoini\tabA,\quark:\quark,}
\def\mergejoini#1:#2,{%
	\ifx\quark#1\the\tabjoin
	\else
		\def\mergejoinii##1,#2:##2,{%
			\ifx\quark##2\else
				\tabjoin\expandafter{\the\tabjoin#1 : #2 : ##2\par}%
				\expandafter\mergejoinii\expandafter,%
			\fi
		}%
		\expandafter\mergejoinii\expandafter,\tabB,#2:\quark,%
		\expandafter\mergejoini
	\fi
}
\mergejoin
\bye


% Name/Age
person_age('Jonah',  27).
person_age('Alan',   18).
person_age('Glory',  28).
person_age('Popeye', 18).
person_age('Alan',   28).

% Character/Nemesis
character_nemisis('Jonah', 'Whales').
character_nemisis('Jonah', 'Spiders').
character_nemisis('Alan',  'Ghosts').
character_nemisis('Alan',  'Zombies').
character_nemisis('Glory', 'Buffy').

join_and_print :-
	format('Age\tName\tCharacter\tNemisis\n\n'),
	forall(
		(person_age(Person, Age), character_nemisis(Person, Nemesis)),
		format('~w\t~w\t~w\t\t~w\n', [Age, Person, Person, Nemesis])
	).


Structure tabA
  age.i
  name.s
EndStructure

Structure tabB
  char_name.s
  nemesis.s
EndStructure

NewList listA.tabA()
NewList listB.tabB()

Macro SetListA(c_age, c_name)
  AddElement(listA()) : listA()\age = c_age : listA()\name = c_name
EndMacro

Macro SetListB(c_char, c_nem)
  AddElement(listB()) : listB()\char_name = c_char : listB()\nemesis = c_nem
EndMacro

SetListA(27, "Jonah")   : SetListA(18, "Alan") : SetListA(28, "Glory")
SetListA(18, "Popeye")  : SetListA(28, "Alan")

SetListB("Jonah", "Whales") : SetListB("Jonah", "Spiders")
SetListB("Alan", "Ghosts")  : SetListB("Alan", "Zombies")
SetListB("Glory", "Buffy")

If OpenConsole("Hash_join")
  ForEach listA()
    PrintN("Input A = "+Str(listA()\age)+~"\t"+listA()\name)
  Next
  PrintN("")
  ForEach listB()
    PrintN("Input B = "+listB()\char_name+~"\t"+listB()\nemesis)
  Next
  PrintN(~"\nOutput\nA.Age\tA.Name\tB.Char.\tB.Nemesis")
  ForEach listA()
    ForEach listB()
      If listA()\name = listB()\char_name
        PrintN(Str(listA()\age)+~"\t"+listA()\name+~"\t"+
               listB()\char_name+~"\t"+listB()\nemesis)
      EndIf
    Next
  Next
  Input()
EndIf


import sun.misc.Signal;
import sun.misc.SignalHandler;

public class ExampleSignalHandler {
    public static void main(String... args) throws InterruptedException {
        final long start = System.nanoTime();
        Signal.handle(new Signal("INT"), new SignalHandler() {
            public void handle(Signal sig) {
                System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
                System.exit(0);
            }
        });
        int counter = 0;
        while(true) {
            System.out.println(counter++);
            Thread.sleep(500);
        }
    }
}


(function(){
    var count=0
        secs=0

    var i= setInterval( function (){
        count++
        secs+=0.5
        console.log(count)
    }, 500);

    process.on('SIGINT', function() {
        clearInterval(i)
        console.log(secs+' seconds elapsed');
        process.exit()
    });
})();


/* Handle a signal, is jsish */

var gotime = strptime();
var looping = true;
var loops = 1;

function handler() {
    printf("Elapsed time: %ds\n", (strptime() - gotime) / 1000);
    looping = false;
}

Signal.callback(handler, 'SIGINT');
Signal.handle('SIGINT');

while (looping) {
    puts(loops++);
    Event.update(500);
}


Public Sub Main()

PRINT "Hello world!"

End


public class Harshad{
    private static long sumDigits(long n){
        long sum = 0;
        for(char digit:Long.toString(n).toCharArray()){
            sum += Character.digit(digit, 10);
        }
        return sum;
    }
    public static void main(String[] args){
        for(int count = 0, i = 1; count < 20;i++){
            if(i % sumDigits(i) == 0){
                System.out.println(i);
                count++;
            }
        }
        System.out.println();
        for(int i = 1001; ; i++){
            if(i % sumDigits(i) == 0){
                System.out.println(i);
                break;
            }
        }
    }
}


function isHarshad(n) {
    var s = 0;
    var n_str = new String(n);
    for (var i = 0; i < n_str.length; ++i) {
        s += parseInt(n_str.charAt(i));
    }
    return n % s === 0;
}

var count = 0;
var harshads = [];

for (var n = 1; count < 20; ++n) {
    if (isHarshad(n)) {
        count++;
        harshads.push(n);
    }
}

console.log(harshads.join(" "));

var h = 1000;
while (!isHarshad(++h));
console.log(h);


array1 = .array~of("Rick", "Mike", "David")
array2 = .array~of("555-9862", "555-5309", "555-6666")

-- if the index items are constrained to string objects, this can
-- be a directory too.
hash = .table~new

loop i = 1 to array1~size
    hash[array1[i]] = array2[i]
end
Say 'Enter a name'
Parse Pull name
Say name '->' hash[name]


declare
  fun {ZipRecord Keys Values}
     {List.toRecord unit {List.zip Keys Values MakePair}}
  end

  fun {MakePair A B}
     A#B
  end
in
  {Show {ZipRecord [a b c] [1 2 3]}}


program HashFromTwoArrays (Output);

uses
  contnrs;

var
  keys:   array[1..3] of string  = ('a', 'b', 'c');
  values: array[1..3] of integer = ( 1,   2,   3 );
  hash:   TFPDataHashTable;
  i:      integer;

begin
  hash := TFPDataHashTable.Create;
  for i := low(keys) to high(keys) do
    hash.add(keys[i], @values[i]);
  writeln ('Length of hash table: ', hash.Count);
  hash.Destroy;
end.


from collections import defaultdict

def hashJoin(table1, index1, table2, index2):
    h = defaultdict(list)
    # hash phase
    for s in table1:
        h[s[index1]].append(s)
    # join phase
    return [(s, r) for r in table2 for s in h[r[index2]]]

table1 = [(27, "Jonah"),
          (18, "Alan"),
          (28, "Glory"),
          (18, "Popeye"),
          (28, "Alan")]
table2 = [("Jonah", "Whales"),
          ("Jonah", "Spiders"),
          ("Alan", "Ghosts"),
          ("Alan", "Zombies"),
          ("Glory", "Buffy")]

for row in hashJoin(table1, 1, table2, 0):
    print(row)


#lang racket
(struct A  (age name))
(struct B  (name nemesis))
(struct AB (name age nemesis) #:transparent)

(define Ages-table
  (list (A 27 "Jonah") (A 18 "Alan")
        (A 28 "Glory") (A 18 "Popeye")
        (A 28 "Alan")))

(define Nemeses-table
  (list
   (B "Jonah" "Whales") (B "Jonah" "Spiders")
   (B "Alan" "Ghosts") (B "Alan" "Zombies")
   (B "Glory" "Buffy")))

;; Hash phase
(define name->ages#
  (for/fold ((rv (hash)))
    ((a (in-list Ages-table)))
    (match-define (A age name) a)
    (hash-update rv name (λ (ages) (append ages (list age))) null)))

;; Join phase
(for*/list
    ((b (in-list Nemeses-table))
     (key (in-value (B-name b)))
     (age (in-list (hash-ref name->ages# key))))
  (AB key age (B-nemesis b)))


sub hash-join(@a, &a, @b, &b) {
    my %hash := @b.classify(&b);

    @a.map: -> $a {
        |(%hash{a $a} // next).map: -> $b { [$a, $b] }
    }
}

# Testing:

my @A =
    [27, "Jonah"],
    [18, "Alan"],
    [28, "Glory"],
    [18, "Popeye"],
    [28, "Alan"],
;

my @B =
    ["Jonah", "Whales"],
    ["Jonah", "Spiders"],
    ["Alan", "Ghosts"],
    ["Alan", "Zombies"],
    ["Glory", "Buffy"],
;

.say for hash-join @A, *[1], @B, *[0];


ccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0)

function timeit()
    ticks = 0
    try
        while true
            sleep(0.5)
            ticks += 1
            println(ticks)
        end
    catch
    end
end

@time timeit()
println("Done.")


// version 1.1.3

import sun.misc.Signal
import sun.misc.SignalHandler

fun main(args: Array<String>) {
    val startTime = System.currentTimeMillis()

    Signal.handle(Signal("INT"), object : SignalHandler {
        override fun handle(sig: Signal) {
            val elapsedTime = (System.currentTimeMillis() - startTime) / 1000.0
            println("\nThe program has run for $elapsedTime seconds")
            System.exit(0)
        }
    })

    var i = 0
    while(true) {
        println(i++)
        Thread.sleep(500)
    }
}


nomainwin
WindowHeight=DisplayHeight
open "Handle a signal" for graphics as #1
#1 "trapclose [quit]"
#1 "down;setfocus;place 10 20"
#1 "\Press CTRL + C to stop."
#1 "when characterInput [keyPressed]"
start=time$("ms")
timer 500, [doPrint]
wait
[quit] close #1:end

[doPrint]
  if sigInt then
    timer 0
    #1 "\Seconds elapsed: ";(time$("ms")-start)/1000
   else
    i=i+1
    if i mod 20 = 0 then #1 "cls;place 10 20"
    #1 "\";i
  end if
  wait

[keyPressed]
  if len(Inkey$)>1 then
    if left$(Inkey$,1)=chr$(8) then sigCtrl=1 else sigCtrl=0
  end if
  if sigCtrl=1 and Inkey$=chr$(3) then sigInt=1
  wait


# Several ways to do it
"Hello world!";

Print("Hello world!\n"); # No EOL appended

Display("Hello world!");

f := OutputTextUser();
WriteLine(f, "Hello world!\n");
CloseStream(f);


def is_harshad:
 def digits: tostring | [explode[] | ([.]| implode) | tonumber];
 if . >= 1 then (. % (digits|add)) == 0
 else false
 end ;

# produce a stream of n Harshad numbers
def harshads(n):
  # [candidate, count]
  def _harshads:
    if .[0]|is_harshad then .[0], ([.[0]+1, .[1]-1]| _harshads)
    elif .[1] > 0 then [.[0]+1, .[1]] | _harshads
    else empty
    end;
  [1, n] | _harshads ;

# First Harshad greater than n where n >= 0
def harshad_greater_than(n):
  # input: next candidate
  def _harshad:
    if is_harshad then .
    else .+1 | _harshad
    end;
  (n+1) | _harshad ;

# Task:
[ harshads(20), "...", harshad_greater_than(1000)]


isharshad(x)   = x % sum(digits(x)) == 0
nextharshad(x) = begin while !isharshad(x+1) x += 1 end; return x + 1 end

function harshads(n::Integer)
	h = Vector{typeof(n)}(n)
	h[1] = 1
	for j in 2:n
		h[j] = nextharshad(h[j-1])
	end
	return h
end

println("First 20 harshad numbers: ", join(harshads(20), ", "))
println("First harshad number after 1001: ", nextharshad(1000))


my @keys = qw(a b c);
my @vals = (1, 2, 3);
my %hash;
@hash{@keys} = @vals;


with javascript_semantics
function make_hash(sequence keyarray, sequence valuearray)
    integer dict = new_dict()
    for i=1 to length(keyarray) do
        setd(keyarray[i],valuearray[i],dict)
--      setd(keyarray[i],i,dict)
    end for
    return dict
end function

constant keyarray   = {1,"two",PI}
constant valuearray = {"one",2,PI}
integer dict = make_hash(keyarray,valuearray)
?getd(1,dict)
?getd("two",dict)
?getd(PI,dict)
--?valuearray[getd(1,dict)]


include ..\Utilitys.pmt

def getd    /# array key -- array data #/
    swap 1 get rot find nip
    dup if
        swap 2 get rot get nip
    else
        drop "Unfound"
    endif
enddef

( ( 1 "two" PI ) ( "one" 2 PI ) )   /# keys / data #/

1 getd print nl
"two" getd print nl
PI getd tostr print nl
3 getd print


BEGIN # find some harmonic numbers, Hn is the sum if the reciprocals of 1..n #
    # returns the first n Harmonic numbers #
    OP   HARMONIC = ( INT n )[]REAL:
         BEGIN
            [ 1 : n ]REAL h;
            h[ 1 ] := 1;
            FOR i FROM 2 TO n DO
                h[ i ] := h[ i - 1 ] + ( 1 / i )
            OD;
            h
         END # HARMONIC # ;
    # find the first 20 000 harmonic numbers #
    []REAL h = HARMONIC 20 000;
    # show the first 20 harmonic numbers #
    FOR i TO 20 DO
        print( ( whole( i, -2 ), ":", fixed( h[ i ], -14, 8 ), newline ) )
    OD;
    # find the positions of the first harmonic number > n where n in 1... #
    INT  rqd int  := 1;
    REAL rqd real := 1;
    FOR i TO UPB h DO
        IF h[ i ] > rqd real THEN
            # found the first harmonic number greater than rqd real #
            print( ( "Position of the first harmonic number > ", whole( rqd int, -2 ), ": ", whole( i, 0 ), newline ) );
            rqd int  +:= 1;
            rqd real +:= 1
        FI
    OD
END


/*REXX program demonstrates the  classic hash join algorithm  for two relations.        */
                     S.  =                   ;         R.  =
                     S.1 = 27 'Jonah'        ;         R.1 = "Jonah Whales"
                     S.2 = 18 'Alan'         ;         R.2 = "Jonah Spiders"
                     S.3 = 28 'Glory'        ;         R.3 = "Alan Ghosts"
                     S.4 = 18 'Popeye'       ;         R.4 = "Alan Zombies"
                     S.5 = 28 'Alan'         ;         R.5 = "Glory Buffy"
hash.=                                           /*initialize the  hash  table (array). */
      do #=1  while S.#\=='';   parse var  S.#  age  name          /*extract information*/
      hash.name=hash.name #                      /*build a hash table entry with its idx*/
      end   /*#*/                                /* [↑]  REXX does the heavy work here. */
#=#-1                                            /*adjust for the DO loop  (#)  overage.*/
      do j=1  while R.j\==''                     /*process a nemesis for a name element.*/
      parse var  R.j  x  nemesis                 /*extract the name  and  its nemesis.  */
      if hash.x==''  then do;   #=# + 1          /*Not in hash?  Then a new name; bump #*/
                                S.#=','  x       /*add a new name to the    S   table.  */
                                hash.x=#         /* "  "  "    "   "  "   hash    "     */
                          end                    /* [↑]  this  DO  isn't used today.    */
           do k=1  for words(hash.x);   _=word(hash.x, k)          /*obtain the pointer.*/
           S._=S._  nemesis                      /*add the nemesis ──► applicable hash. */
           end   /*k*/
      end        /*j*/
_='─'                                            /*the character used for the separator.*/
pad=left('', 4)                                  /*spacing used in header and the output*/
say  pad  center('age', 3)   pad   center("name", 20   )   pad    center('nemesis', 30   )
say  pad  center('───', 3)   pad   center(""    , 20, _)   pad    center(''       , 30, _)

      do n=1  for #;      parse  var  S.n    age  name  nems       /*obtain information.*/
      if nems==''  then iterate                                    /*No nemesis?  Skip. */
      say pad right(age,3) pad center(name,20) pad center(nems,30) /*display an  "S".   */
      end   /*n*/                                /*stick a fork in it,  we're all done. */


Table1 = [[27, "Jonah"], [18, "Alan"], [28, "Glory"], [18, "Popeye"], [28, "Alan"]]
Table2 = [["Jonah", "Whales"], ["Jonah", "Spiders"], ["Alan", "Ghosts"], ["Alan", "Zombies"], ["Glory", "Buffy"]]
hTable = []
Qtable = []

for a in table1
	h = hashing(a[2])
	add(htable,[h , a])
next

for b in table2
	h = hashing(b[1])
	for sh in htable
		if sh[1] = h
			 add(qtable, sh[2] + b[2])
		ok
	next
next

print(qtable)

#===============End of Execution=========

func print lst
see "---------------------------------------------------
Age	| Name		|| Name		| Nemesis
---------------------------------------------------
"
for l in lst
	see string(l[1]) + char(9) + "| " + l[2] + copy(char(9),2) + "|| " + l[2] + "    " + char(9) +  "| " + l[3] + nl
next

func Hashing str
r = 0
if len(str) > 4
	r = (ascii(str[1]) + ascii(str[len(str)]) + ascii(str[ceil(len(str) * 0.25)]) + ascii(str[ceil(len(str) * 0.75)]))
else
	for s in str
		r += ascii(s)
	next
ok
return r


function sigintHandle
    k = 1;
    tic
    catchObj = onCleanup(@toc);
    while true
        pause(0.5)
        fprintf('%d\n', k)
        k = k+1;
    end
end


; Mac OSX, BSDs or Linux only, not Windows
(setq start-time (now))

(signal 2 (lambda()
            (println
             (format "Program has run for %d seconds"
                     (- (apply date-value (now))
                        (apply date-value start-time))))
            (exit 0)))

(while (println (++ i))
  (sleep 500))


import times, os, strutils

let t = epochTime()

proc handler() {.noconv.} =
  echo "Program has run for ", formatFloat(epochTime() - t, precision = 0), " seconds."
  quit 0

setControlCHook(handler)

for n in 1 ..< int64.high:
  sleep 500
  echo n


#load "unix.cma";; (* for sleep and gettimeofday; not needed for the signals stuff per se *)

let start = Unix.gettimeofday ();;

Sys.set_signal Sys.sigint
  (Sys.Signal_handle (fun _signum ->
                        Printf.printf "Ran for %f seconds.\n"
                          (Unix.gettimeofday () -. start);
                        exit 0));;

let rec loop n =
  Printf.printf "%d\n%!" n;
  Unix.sleep 1;
  loop (n + 1)
in
  loop 1;;


*= ! ignore off content of input
\B=Hello world!\! ! Start output with this text.


/ sum of digits of an integer
sumdig: {d::(); (0<){d::d,x!10; x%:10}/x; +/d}
/ Test if an integer is a Harshad number
isHarshad: {:[x!(sumdig x); 0; 1]} / Returns 1 if Harshad
/ Generate x Harshad numbers starting from y and display the list
hSeries: {harshad::();i:y;while[(x-#harshad)>0;:[isHarshad i; harshad::(harshad,i)]; i+:1];harshad}


// version 1.1

fun sumDigits(n: Int): Int = when {
        n <= 0 -> 0
        else   -> {
            var sum = 0
            var nn = n
            while (nn > 0) {
                sum += nn % 10
                nn /= 10
            }
            sum
        }
    }

fun isHarshad(n: Int): Boolean = (n % sumDigits(n) == 0)

fun main(args: Array<String>) {
    println("The first 20 Harshad numbers are:")
    var count = 0
    var i = 0

    while (true) {
        if (isHarshad(++i)) {
            print("$i ")
            if (++count == 20) break
        }
    }

    println("\n\nThe first Harshad number above 1000 is:")
    i = 1000

    while (true) {
        if (isHarshad(++i)) {
            println(i)
            return
        }
    }
}


$keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array_combine($keys, $values);


(let (Keys '(one two three)  Values (1 2 3))
   (mapc println
      (mapcar cons Keys Values) ) )


array indices = ({ "a", "b", 42 });
array values  = ({ Image.Color(0,0,0), "hello", "world" });
mapping m = mkmapping( indices, values );
write("%O\n", m);


H: function [n][
    sum map 1..n => reciprocal
]

firstAbove: function [lim][
    i: 1
    while ø [
        if lim < to :floating H i ->
            return i
        i: i + 1
    ]
]

print "The first 20 harmonic numbers:"
print map 1..20 => H

print ""
loop 1..4 'l [
    print ["Position of first term >" l ":" firstAbove l]
]


# syntax: GAWK -f HARMONIC_SERIES.AWK
# converted from FreeBASIC
BEGIN {
    limit = 20
    printf("The first %d harmonic numbers:\n",limit)
    for (n=1; n<=limit; n++) {
      h += 1/n
      printf("%2d %11.8f\n",n,h)
    }
    print("")
    h = 1
    n = 2
    for (i=2; i<=10; i++) {
      while (h < i) {
        h += 1/n
        n++
      }
      printf("The first harmonic number > %2d is %11.8f at position %d\n",i,h,n-1)
    }
    exit(0)
}


h = 0.0

print "The first twenty harmonic numbers are:"
for n = 1 to 20
	h += 1.0 / n
	print n, h
next n
print

h = 1 : n = 2
for i = 2 to 10
	while h < i
		h += 1.0 / n
		n += 1
	end while
	print "The first harmonic number greater than "; i; " is "; h; ", at position "; n-1
next i
end


#include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/multiprecision/gmp.hpp>

using integer = boost::multiprecision::mpz_int;
using rational = boost::rational<integer>;

class harmonic_generator {
public:
    rational next() {
        rational result = term_;
        term_ += rational(1, ++n_);
        return result;
    }
    void reset() {
        n_ = 1;
        term_ = 1;
    }
private:
    integer n_ = 1;
    rational term_ = 1;
};

int main() {
    std::cout << "First 20 harmonic numbers:\n";
    harmonic_generator hgen;
    for (int i = 1; i <= 20; ++i)
        std::cout << std::setw(2) << i << ". " << hgen.next() << '\n';

    rational h;
    for (int i = 1; i <= 80; ++i)
        h = hgen.next();
    std::cout << "\n100th harmonic number: " << h << "\n\n";

    int n = 1;
    hgen.reset();
    for (int i = 1; n <= 10; ++i) {
        if (hgen.next() > n)
            std::cout << "Position of first term > " << std::setw(2) << n++ << ": " << i << '\n';
    }
}


def hashJoin(table1, index1, table2, index2)
  # hash phase
  h = table1.group_by {|s| s[index1]}
  h.default = []
  # join phase
  table2.collect {|r|
    h[r[index2]].collect {|s| [s, r]}
  }.flatten(1)
end

table1 = [[27, "Jonah"],
          [18, "Alan"],
          [28, "Glory"],
          [18, "Popeye"],
          [28, "Alan"]]
table2 = [["Jonah", "Whales"],
          ["Jonah", "Spiders"],
          ["Alan", "Ghosts"],
          ["Alan", "Zombies"],
          ["Glory", "Buffy"]]

hashJoin(table1, 1, table2, 0).each { |row| p row }


sqliteconnect #mem, ":memory:"

#mem execute("CREATE TABLE t_age(age,name)")
#mem execute("CREATE TABLE t_name(name,nemesis)")

#mem execute("INSERT INTO t_age VALUES(27,'Jonah')")
#mem execute("INSERT INTO t_age VALUES(18,'Alan')")
#mem execute("INSERT INTO t_age VALUES(28,'Glory')")
#mem execute("INSERT INTO t_age VALUES(18,'Popeye')")
#mem execute("INSERT INTO t_age VALUES(28,'Alan')")

#mem execute("INSERT INTO t_name VALUES('Jonah','Whales')")
#mem execute("INSERT INTO t_name VALUES('Jonah','Spiders')")
#mem execute("INSERT INTO t_name VALUES('Alan','Ghosts')")
#mem execute("INSERT INTO t_name VALUES('Alan','Zombies')")
#mem execute("INSERT INTO t_name VALUES('Glory','Buffy')")

#mem execute("SELECT *,t_age.name FROM t_age LEFT JOIN t_name ON t_name.name = t_age.name")
WHILE  #mem hasanswer()
	#row		= #mem #nextrow()
	age		= #row age()
	name$		= #row name$()
	nemesis$	= #row nemesis$()
print age;" ";name$;" ";nemesis$
WEND


use std::collections::HashMap;
use std::hash::Hash;

// If you know one of the tables is smaller, it is best to make it the second parameter.
fn hash_join<A, B, K>(first: &[(K, A)], second: &[(K, B)]) -> Vec<(A, K, B)>
where
    K: Hash + Eq + Copy,
    A: Copy,
    B: Copy,
{
    let mut hash_map = HashMap::new();

    // hash phase
    for &(key, val_a) in second {
        // collect all values by their keys, appending new ones to each existing entry
        hash_map.entry(key).or_insert_with(Vec::new).push(val_a);
    }

    let mut result = Vec::new();
    // join phase
    for &(key, val_b) in first {
        if let Some(vals) = hash_map.get(&key) {
            let tuples = vals.iter().map(|&val_a| (val_b, key, val_a));
            result.extend(tuples);
        }
    }

    result
}

fn main() {
    let table1 = [("Jonah", 27), ("Alan", 18), ("Glory", 28), ("Popeye", 18), ("Alan", 28)];
    let table2 = [
        ("Jonah", "Whales"), ("Jonah", "Spiders"), ("Alan", "Ghosts"),
        ("Alan", "Zombies"), ("Glory", "Buffy")
    ];
    let result = hash_join(&table1, &table2);
    println!("Age | Character Name | Nemesis");
    println!("----|----------------|--------");
    for (age, name, nemesis) in result {
        println!("{:<3} | {:^14} | {}", age, name, nemesis);
    }
}


my $start = time;  # seconds since epohc
my $arlm=5;  # every 5 seconds show how we're doing
my $i;

$SIG{QUIT} = sub
   {print " Ran for ", time - $start, " seconds.\n"; die; };
$SIG{INT} = sub
   {print " Running for ", time - $start, " seconds.\n"; };
$SIG{ALRM} = sub
   {print " After $arlm  seconds i= $i. Executing for ",  time - $start, " seconds.\n";  alarm $arlm };

alarm $arlm;  # trigger ALaRM after we've run  for a while

print " ^C to inerrupt, ^\\ to quit, takes a break at $arlm seconds \n";

while ( 1 ) {
   for ( $w=11935000; $w--; $w>0 ){}; # spinning is bad, but hey it's only a demo

    print (  ++$i," \n");
            }


without js
allow_break(false)   -- by default Ctrl C terminates the program
puts(1,"Press Ctrl C\n")
atom t = time()
integer i = 1
while 1 do
    sleep(0.5)
    ?i
    if check_break() then exit end if
    i += 1
end while
printf(1,"The program has run for %3.2f seconds\n",{time()-t})


<?php
declare(ticks = 1);

$start = microtime(YES);

function mySigHandler() {
  global $start;
  $elapsed = microtime(YES) - $start;
  echo "Ran for $elapsed seconds.\n";
  exit();
}

pcntl_signal(SIGINT, 'mySigHandler');

for ($n = 0; ; usleep(500000)) // 0.5 seconds
   echo ++$n, "\n";
?>


func hello <main>
{
   print("Hello world!")
}


HAI 1.3

HOW IZ I digsummin YR num
    I HAS A digsum ITZ 0
    IM IN YR LOOP
        num, O RLY?
            YA RLY
                digsum R SUM OF digsum AN MOD OF num AN 10
                num R QUOSHUNT OF num AN 10
            NO WAI, FOUND YR digsum
        OIC
    IM OUTTA YR LOOP
IF U SAY SO

I HAS A found ITZ 0

IM IN YR finder UPPIN YR n
    I HAS A n ITZ SUM OF n AN 1
    I HAS A digsum ITZ I IZ digsummin YR n MKAY

    NOT MOD OF n AN digsum, O RLY?
        YA RLY
            DIFFRINT found AN BIGGR OF found AN 20, O RLY?
                YA RLY
                    VISIBLE n " "!
                    found R SUM OF found AN 1
            OIC

            DIFFRINT n AN SMALLR OF n AN 1000, O RLY?
                YA RLY, VISIBLE ":)" n, GTFO
            OIC
    OIC
IM OUTTA YR finder

KTHXBYE


function isHarshad(n)
    local s=0
    local n_str=tostring(n)
    for i=1,#n_str do
        s=s+tonumber(n_str:sub(i,i))
    end
    return n%s==0
end

local count=0
local harshads={}
local n=1

while count<20 do
    if isHarshad(n) then
        count=count+1
        table.insert(harshads, n)
    end
    n=n+1
end

print(table.concat(harshads, " "))

local h=1001
while not isHarshad(h) do
    h=h+1
end
print(h)


vars keys = { 1 a b c};
vars vals = { 2 3 valb valc};
vars i;
;;; Create hash table
vars ht = newmapping([], 500, 0, true);
;;; Loop over input arrays (vectors)
for i from 1 to length(keys) do
  vals(i) -> ht(keys(i));
endfor;


% push our arrays
 [/a /b /c /d /e] [1 2 3 4 5]
% create a dict with it
{aload pop} dip let currentdict end
% show that we have created the hash
 {= =} forall


function create_hash ([array] $keys, [array] $values) {
    $h = @{}
    if ($keys.Length -ne $values.Length) {
        Write-Error -Message "Array lengths do not match" `
                    -Category InvalidData `
                    -TargetObject $values
    } else {
        for ($i = 0; $i -lt $keys.Length; $i++) {
            $h[$keys[$i]] = $values[$i]
        }
    }
    return $h
}


% this one with side effect hash table creation

:-dynamic hash/2.

make_hash([],[]).
make_hash([H|Q],[H1|Q1]):-
	assert(hash(H,H1)),
	make_hash(Q,Q1).

:-make_hash([un,deux,trois],[[a,b,c],[d,e,f],[g,h,i]])

% this one without side effects

make_hash_pure([],[],[]).
make_hash_pure([H|Q],[H1|Q1],[hash(H,H1)|R]):-
	make_hash_pure(Q,Q1,R).

:-make_hash_pure([un,deux,trois],[[a,b,c],[d,e,f],[g,h,i]],L),findall(M,(member(M,L),assert(M)),L).


       IDENTIFICATION DIVISION.
       PROGRAM-ID. HARMONIC.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 VARS.
          03 N           PIC 9(5) VALUE ZERO.
          03 HN          PIC 9(2)V9(12) VALUE ZERO.
          03 INT         PIC 99 VALUE ZERO.
       01 OUT-VARS.
          03 POS         PIC Z(4)9.
          03 FILLER      PIC X(3) VALUE SPACES.
          03 H-OUT       PIC Z9.9(12).

       PROCEDURE DIVISION.
       BEGIN.
           DISPLAY "First 20 harmonic numbers:"
           PERFORM SHOW-HARMONIC 20 TIMES.
           DISPLAY SPACES.
           MOVE ZERO TO N, HN.
           DISPLAY "First harmonic number to exceed whole number:"
           PERFORM EXCEED-INT 10 TIMES.
           STOP RUN.

       SHOW-HARMONIC.
           PERFORM NEXT-HARMONIC.
           MOVE HN TO H-OUT.
           DISPLAY H-OUT.

       EXCEED-INT.
           ADD 1 TO INT.
           PERFORM NEXT-HARMONIC UNTIL HN IS GREATER THAN INT.
           MOVE N TO POS.
           MOVE HN TO H-OUT.
           DISPLAY OUT-VARS.

       NEXT-HARMONIC.
           ADD 1 TO N.
           COMPUTE HN = HN + 1 / N.


USING: formatting grouping io kernel lists lists.lazy math
math.functions math.ranges math.statistics math.text.english
prettyprint sequences tools.memory.private ;

! Euler-Mascheroni constant
CONSTANT: γ 0.5772156649

: Hn-approx ( n -- ~Hn )
    [ log γ + 1 2 ] [ * /f + 1 ] [ sq 12 * /f - ] tri ;

: lharmonics ( -- list ) 1 lfrom [ Hn-approx ] lmap-lazy ;

: first-gt ( m -- n ) lharmonics swap '[ _ < ] lwhile llength ;

"First twenty harmonic numbers as mixed numbers:" print
100 [1,b] [ recip ] map cum-sum
[ 20 head 5 group simple-table. nl ]
[ "One hundredth:" print last . nl ] bi

"(zero based) Index of first value:" print
10 [1,b] [
    dup first-gt [ commas ] [ 1 + number>text ] bi
    "  greater than %2d: %6s (term number %s)\n" printf
] each


warnings off

1.000.000.000.000.000 drop constant 1.0fx  \ fractional part is 15 decimal digits.

: .h  ( n -- )
    s>d <#  14 for # next  [char] . hold #s #> type space ;

1.0fx 1 2constant first-harmonic

: round  5 + 10 / ;

: next-harmonic ( h n -- h' n' )
    1+ tuck [ 1.0fx 10 * ] literal swap / round + swap ;

: task1
    first-harmonic  19 for  over cr .h next-harmonic  next 2drop ;

: task2
    first-harmonic
    11 1 do
        begin over i 1.0fx * <= while
            next-harmonic
        repeat
        dup .
    loop 2drop ;

." The first 10 harmonic numbers: " task1 cr cr
." The nth index of the first harmonic number that exceeds the nth integer: " cr task2 cr
bye


dim as double h = 0.0
dim as uinteger n, i

print "The first twenty harmonic numbers are:"
for n = 1 to 20
    h += 1.0/n
    print n, h
next n

h = 1 : n = 2
for i=2 to 10
    while h<i
        h+=1.0/n
        n+=1
    wend
    print "The first harmonic number greater than ";i;" is ";h;", at position ";n-1
next i


package main

import (
    "fmt"
    "math/big"
)

func harmonic(n int) *big.Rat {
    sum := new(big.Rat)
    for i := int64(1); i <= int64(n); i++ {
        r := big.NewRat(1, i)
        sum.Add(sum, r)
    }
    return sum
}

func main() {
    fmt.Println("The first 20 harmonic numbers and the 100th, expressed in rational form, are:")
    numbers := make([]int, 21)
    for i := 1; i <= 20; i++ {
        numbers[i-1] = i
    }
    numbers[20] = 100
    for _, i := range numbers {
        fmt.Printf("%3d : %s\n", i, harmonic(i))
    }

    fmt.Println("\nThe first harmonic number to exceed the following integers is:")
    const limit = 10
    for i, n, h := 1, 1, 0.0; i <= limit; n++ {
        h += 1.0 / float64(n)
        if h > float64(i) {
            fmt.Printf("integer = %2d  -> n = %6d  ->  harmonic number = %9.6f (to 6dp)\n", i, n, h)
            i++
        }
    }
}


def join[Type](left: Seq[Seq[Type]], right: Seq[Seq[Type]]) = {
    val hash = right.groupBy(_.head) withDefaultValue Seq()
    left.flatMap(cols => hash(cols.last).map(cols ++ _.tail))
}

// Example:

val table1 = List(List("27", "Jonah"),
                  List("18", "Alan"),
                  List("28", "Glory"),
                  List("18", "Popeye"),
                  List("28", "Alan"))
val table2 = List(List("Jonah", "Whales"),
                  List("Jonah", "Spiders"),
                  List("Alan", "Ghosts"),
                  List("Alan", "Zombies"),
                  List("Glory", "Buffy"))

println(join(table1, table2) mkString "\n")


(use srfi-42)

(define ages '((27 Jonah) (18 Alan) (28 Glory) (18 Popeye) (28 Alan)))

(define nemeses '((Jonah Whales) (Jonah Spiders) (Alan Ghosts)
                  (Alan Zombies) (Glory Buffy)
                  (unknown nothing)))

(define hash (make-hash-table 'equal?))

(dolist (item ages)
  (hash-table-push! hash (last item) (car item)))

(do-ec
  (: person nemeses)
  (:let name (car person))
  (if (hash-table-exists? hash name))
  (: age (~ hash name))
  (print (list (list age name)
               person)))


#!/usr/bin/picolisp /usr/lib/picolisp/lib.l

(push '*Bye '(println (*/ (usec) 1000000)) '(prinl))

(let Cnt 0
   (loop
      (println (inc 'Cnt))
      (wait 500) ) )


handler: procedure options (main);
   declare i fixed binary (31);
   declare (start_time, finish_time) float (18);
   on attention begin;
      finish_time = secs();
      put skip list ('elapsed time =', finish_time - start_time, 'secs');
      stop;
   end;

   start_time = secs();
   do i = 1 by 1;
      delay (500);
      put skip list (i);
   end;
end handler;


$Start_Time = (Get-date).second
Write-Host "Type CTRL-C to Terminate..."
$n = 1
Try
{
    While($true)
    {
        Write-Host $n
        $n ++
        Start-Sleep -m 500
    }
}
Finally
{
    $End_Time = (Get-date).second
    $Time_Diff = $End_Time - $Start_Time
    Write-Host "Total time in seconds"$Time_Diff
}


CompilerIf #PB_Compiler_OS<>#PB_OS_Windows
  CompilerError "This code is Windows only"
CompilerEndIf

Global Quit, i, T0=ElapsedMilliseconds(), T1

Procedure CtrlC()
  T1=ElapsedMilliseconds()
  Quit=1
  While i: Delay(1): Wend
EndProcedure

If OpenConsole()
  SetConsoleCtrlHandler_(@CtrlC(),#True)
  While Not Quit
    PrintN(Str(i))
    i+1
    Delay(500)
  Wend
  PrintN("Program has run for "+StrF((T1-T0)/1000,3)+" seconds.")
  Print ("Press ENTER to exit."):Input(): i=0
EndIf


import time

def counter():
    n = 0
    t1 = time.time()
    while True:
        try:
            time.sleep(0.5)
            n += 1
            print n
        except KeyboardInterrupt, e:
            print 'Program has run for %5.3f seconds.' % (time.time() - t1)
            break

counter()


nextHarshad =
  NestWhile[# + 1 &, # + 1, ! Divisible[#, [email protected]@#] &] &;
[email protected]@NestList[nextHarshad, 0, 20];
[email protected]@1000;


            NORMAL MODE IS INTEGER

            INTERNAL FUNCTION(A,B)
            ENTRY TO REM.
            FUNCTION RETURN A-A/B*B
            END OF FUNCTION

            INTERNAL FUNCTION(I)
            ENTRY TO DSUM.
            SUM = 0
            REST = I
DIGIT       WHENEVER REST.NE.0
                SUM = SUM + REM.(REST,10)
                REST = REST/10
                TRANSFER TO DIGIT
            END OF CONDITIONAL
            FUNCTION RETURN SUM
            END OF FUNCTION

            INTERNAL FUNCTION(I)
            ENTRY TO NEXT.
LOOP        THROUGH LOOP, FOR NX=I+1, 1, REM.(NX,DSUM.(NX)).E.0
            FUNCTION RETURN NX
            END OF FUNCTION

            PRINT COMMENT $ FIRST 20 HARSHAD NUMBERS:$
            H = 0
            N = 0
HARSHD      WHENEVER N.LE.1000
                N = NEXT.(N)
                H = H + 1
                WHENEVER H.LE.20, PRINT FORMAT HSHD, H, N
                TRANSFER TO HARSHD
            END OF CONDITIONAL

            PRINT FORMAT THSND, N

            VECTOR VALUES HSHD = $8HHARSHAD(,I2,4H) = ,I2*$
            VECTOR VALUES THSND =
          0     $34HFIRST HARSHAD NUMBER ABOVE 1000 = ,I4*$

            END OF PROGRAM


function v = isharshad(n)
	v = isinteger(n) && ~mod(n,sum(num2str(n)-'0'));
end;


Dim keys.s(3)
Dim vals.s(3)
NewMap Hash.s()

keys(0)="a" : keys(1)="b" : keys(2)="c" : keys(3)="d"
vals(0)="1" : vals(1)="2" : vals(2)="3" : vals(3)="4"
For n = 0 To 3
    Hash(keys(n))= vals(n)
Next
ForEach Hash()
   Debug Hash()
Next


keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = {key: value for key, value in zip(keys, values)}


# Set up hash table
keys <- c("John Smith", "Lisa Smith", "Sam Doe", "Sandra Dee", "Ted Baker")
values <- c(152, 1, 254, 152, 153)
names(values) <- keys
# Get value corresponding to a key
values["Sam Doe"]                          # vals["Sam Doe"]
# Get all keys corresponding to a value
names(values)[values==152]                 # "John Smith" "Sandra Dee"


import Data.List (find)
import Data.Ratio

--------------------- HARMONIC SERIES --------------------

harmonic :: [Rational]
harmonic =
  scanl1
    (\a x -> a + 1 / x)
    [1 ..]

-------------------------- TESTS -------------------------
main :: IO ()
main = do
  putStrLn "First 20 terms:"
  mapM_ putStrLn $
    showRatio <$> take 20 harmonic

  putStrLn "\n100th term:"
  putStrLn $ showRatio (harmonic !! 99)
  putStrLn ""

  putStrLn "One-based indices of first terms above threshold values:"
  let indexedHarmonic = zip [0 ..] harmonic
  mapM_
    putStrLn
    $ fmap
      ( showFirstLimit
          <*> \n -> find ((> n) . snd) indexedHarmonic
      )
      [1 .. 10]

-------------------- DISPLAY FORMATTING ------------------

showFirstLimit n (Just (i, r)) =
  "Term "
    <> show (succ i)
    <> " is the first above "
    <> show (numerator n)

showRatio :: Ratio Integer -> String
showRatio =
  ((<>) . show . numerator)
    <*> (('/' :) . show . denominator)


# include "rational"; # a reminder

def harmonic:
  reduce range(1; 1+.) as $i ( r(0;1);
    radd(.; r(1; $i) ));

def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;

def task1:
  "The first 20 harmonic numbers and the 100th, expressed in rational form, are:",
  (range(1;21), 100
   | "\(.) : \(harmonic|rpp)" );

def task2($limit):
  "The first harmonic number to exceed the following integers is:",
      limit($limit;
    foreach range(0; infinite) as $n (
      {i: 1, n: 1, h: r(0;1)};
      .emit = false
      | .h = radd(.h; r(1; .n))
      | .i as $i
      | if .h | rgreaterthan($i)
        then .emit = "integer = \(.i|lpad(2))  -> n = \(.n| lpad(6))  ->  harmonic number = \(.h|r_to_decimal(6)) (to 6dp)"
	| .i += 1
        else .
        end
        | .n += 1;
      select(.emit).emit) );

task1, "", task2(10)


const memoizer = [BigFloat(1.0), BigFloat(1.5)]

"""
    harmonic(n::Integer)::BigFloat
Calculates harmonic numbers. The integer argument `n` should be positive.
"""
function harmonic(n::Integer)::BigFloat
    if n < 0
        throw(DomainError(n))
    elseif n == 0
        return BigFloat(0.0)   # by convention
    elseif length(memoizer) >= n
        return memoizer[n]
    elseif length(memoizer) + 1 == n
        h = memoizer[end] + BigFloat(1.0) / n
        push!(memoizer, h)
        return h
    elseif n < 1_000_000
        start, x = length(memoizer), memoizer[end]
        for i in start+1:n
            push!(memoizer, (x += big"1.0" / i))
        end
        return memoizer[end]
    else
        # use H(n) = eulergamma + digamma(n + 1), instead, if memory use of memoization too large
        x = n + big"1.0"
        digam = BigFloat()
        ccall((:mpfr_digamma, :libmpfr), Int32, (Ref{BigFloat}, Ref{BigFloat}, Int32), digam, x, 1)
        return Base.MathConstants.eulergamma + digam
    end
end

function testharmonics(upperlimit = 11)
    n = 1
    while (h = harmonic(n)) < upperlimit
        nextintegerfloor = h < 1.8 ? h > 1.0 : floor(h) > floor(memoizer[n - 1])
        if n < 21 || nextintegerfloor
            println("harmonic($n) = $h")
            nextintegerfloor && println("    $n is also the term number for the first harmonic > $(floor(h))")
        end
        n += 1
    end
end

testharmonics()


nums = HarmonicNumber[Range[15000]];
nums[[;; 20]]
LengthWhile[nums, LessEqualThan[#]] + 1 & /@ Range[10]


import strformat

iterator h(): (int, float) =
  ## Yield the index of the term and its value.
  var n = 1
  var r = 0.0
  while true:
    r += 1 / n
    yield (n, r)
    inc n

echo "First 20 terms of the harmonic series:"
for (idx, val) in h():
  echo &"{idx:2}: {val}"
  if idx == 20: break
echo()

var target = 1.0
for (idx, val) in h():
  if val > target:
    echo &"Index of the first term greater than {target.int:2}: {idx}"
    if target == 10: break
    else: target += 1


func hashJoin(table1, index1, table2, index2) {
    var a = []
    var h = Hash()

    # hash phase
    table1.each { |s|
        h{s[index1]} := [] << s
    }

    # join phase
    table2.each { |r|
        a += h{r[index2]}.map{[_,r]}
    }

    return a
}

var t1  = [[27, "Jonah"],
           [18, "Alan"],
           [28, "Glory"],
           [18, "Popeye"],
           [28, "Alan"]]

var t2  = [["Jonah", "Whales"],
           ["Jonah", "Spiders"],
           ["Alan", "Ghosts"],
           ["Alan", "Zombies"],
           ["Glory", "Buffy"]]

hashJoin(t1, 1, t2, 0).each { .say }


-- setting up the test data

CREATE TABLE people (age NUMBER(3), name varchar2(30));
INSERT INTO people (age, name)
  SELECT 27, 'Jonah'  FROM dual UNION ALL
  SELECT 18, 'Alan'   FROM dual UNION ALL
  SELECT 28, 'Glory'  FROM dual UNION ALL
  SELECT 18, 'Popeye' FROM dual UNION ALL
  SELECT 28, 'Alan'   FROM dual
;

CREATE TABLE nemesises (name varchar2(30), nemesis varchar2(30));
INSERT INTO nemesises (name, nemesis)
  SELECT 'Jonah', 'Whales'  FROM dual UNION ALL
  SELECT 'Jonah', 'Spiders' FROM dual UNION ALL
  SELECT 'Alan' , 'Ghosts'  FROM dual UNION ALL
  SELECT 'Alan' , 'Zombies' FROM dual UNION ALL
  SELECT 'Glory', 'Buffy'   FROM dual
;


#lang racket
(define now current-milliseconds)
(define start (now))
(with-handlers ([exn:break?
                 (λ(x)
                   (define elapsed (/ (- (now) start) 1000.))
                   (displayln (~a "Total time: " elapsed)))])
  (for ([i (in-naturals)])
    (displayln i)
    (sleep 0.5)))


signal(SIGINT).tap: {
    note "Took { now - INIT now } seconds.";
    exit;
}

for 0, 1, *+* ... * {
    sleep 0.5;
    .say;
}


/*REXX program displays integers until a   Ctrl─C  is pressed, then shows the number of */
/*────────────────────────────────── seconds that have elapsed since start of execution.*/
call time 'Reset'                                /*reset the REXX elapsed timer.        */
signal on halt                                   /*HALT: signaled via a  Ctrl─C  in DOS.*/

   do j=1                                        /*start with  unity  and go ye forth.  */
   say right(j,20)                               /*display the integer right-justified. */
   t=time('E')                                   /*get the REXX elapsed time in seconds.*/
                do forever;   u=time('Elapsed')  /* "   "    "     "      "   "    "    */
                if u<t | u>t+.5  then iterate j  /* ◄═══ passed midnight or  ½  second. */
                end   /*forever*/
   end   /*j*/

halt: say  'program HALTed, it ran for'   format(time("ELapsed"),,2)     'seconds.'
                                                 /*stick a fork in it,  we're all done. */


t1 = Time.now

catch :done do
  Signal.trap('INT') do
    Signal.trap('INT', 'DEFAULT') # reset to default
    throw :done
  end
  n = 0
  loop do
    sleep(0.5)
    n += 1
    puts n
  end
end

tdelt = Time.now - t1
puts 'Program has run for %5.3f seconds.' % tdelt


#[cfg(unix)]
fn main() {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::thread;
    use std::time::{Duration, Instant};

    use libc::{sighandler_t, SIGINT};

    // The time between ticks of our counter.
    let duration = Duration::from_secs(1) / 2;

    // "SIGINT received" global variable.
    static mut GOT_SIGINT: AtomicBool = AtomicBool::new(false);

    unsafe {
        // Initially, "SIGINT received" is false.
        GOT_SIGINT.store(false, Ordering::Release);
        // Interrupt handler that handles the SIGINT signal
        unsafe fn handle_sigint() {
            // It is dangerous to perform any system calls in interrupts, so just set the atomic
            // "SIGINT received" global to true when it arrives.
            GOT_SIGINT.store(true, Ordering::Release);
        }
        // Make handle_sigint the signal handler for SIGINT.
        libc::signal(SIGINT, handle_sigint as sighandler_t);
    }

    // Get the start time...
    let start = Instant::now();

    // Integer counter
    let mut i = 0u32;

    // Every `duration`...
    loop {
        thread::sleep(duration);

        // Break if SIGINT was handled
        if unsafe { GOT_SIGINT.load(Ordering::Acquire) } {
            break;
        }

        // Otherwise, increment and display the integer and continue the loop.
        i += 1;
        println!("{}", i);
    }

    // Get the elapsed time.
    let elapsed = start.elapsed();

    // Print the difference and exit
    println!("Program has run for {} seconds", elapsed.as_secs());
}

#[cfg(not(unix))]
fn main() {
    println!("Not supported on this platform");
}


MODULE Harshad;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;

VAR n, i: CARDINAL;

PROCEDURE DigitSum(n: CARDINAL): CARDINAL;
VAR sum: CARDINAL;
BEGIN
    sum := 0;
    WHILE n > 0 DO;
        sum := sum + n MOD 10;
        n := n DIV 10;
    END;
    RETURN sum;
END DigitSum;

PROCEDURE NextHarshad(n: CARDINAL): CARDINAL;
BEGIN
    REPEAT INC(n);
    UNTIL n MOD DigitSum(n) = 0;
    RETURN n;
END NextHarshad;

BEGIN
    n := 0;
    WriteString("First 20 Harshad numbers:");
    WriteLn();
    FOR i := 1 TO 20 DO
        n := NextHarshad(n);
        WriteCard(n, 3);
    END;
    WriteLn();
    WriteString("First Harshad number above 1000: ");
    WriteCard(NextHarshad(1000), 4);
    WriteLn();
END Harshad.


(
  :n () =list
  (n 0 >) (
    n 10 mod list prepend #list
    n 10 div @n
  ) while
  list
) :digits

(dup digits sum mod 0 ==) :harshad?

(
  succ :n
  (n harshad? not) (
    n succ @n
  ) while
  n
) :next-harshad

0 (next-harshad print " " print!) 20 times newline
1000 next-harshad print!


my @keys = <a b c d e>;
my @values = ^5;

my %hash = @keys Z=> @values;

#Alternatively, by assigning to a hash slice:
%hash{@keys} = @values;

# Or to create an anonymous hash:
%( @keys Z=> @values );

# All of these zip forms trim the result to the length of the shorter of their two input lists.
# If you wish to enforce equal lengths, you can use a strict hyperoperator instead:

quietly # suppress warnings about unused hash
{ @keys »=>« @values };  # Will fail if the lists differ in length


[ 'a' 'b' 'c' ] as $keys [ 1 2 3 ] as $vals
$keys $vals combine as $hash


/*REXX program demonstrates  hashing  of a  stemmed array  (from a key or multiple keys)*/
key.=                                            /*names of the nine regular polygons.  */
vals= 'triangle quadrilateral pentagon hexagon heptagon octagon nonagon decagon dodecagon'
key.1='thuhree  vour          phive    sicks   zeaven   ate     nein    den     duzun'
key.2='three    four          five     six     seven    eight   nine    ten     twelve'
key.3='3        4             5        6       7        8       9       10      12'
key.4='III      IV            V        VI      VII      VIII    IX      X       XII'
key.5='iii      iv            v        vi      vii      viii    ix      x       xii'
hash.='───(not defined)───'                      /* [↑]  blanks added to humorous keys  */
                                                 /*      just because it looks prettier.*/
      do k=1  while key.k\==''
      call hash vals,key.k                       /*hash the   keys   to the   values.   */
      end   /*k*/

parse arg query .                                /*obtain what was specified on the C.L.*/
if query\==''  then say 'key:'   left(query,40)   "value:"   hash.query
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
hash: parse arg @val,@key
                do j=1  for words(@key);          map= word(@key, j)
                                             hash.map= word(@val, j)
                end   /*j*/
      return


# Project : Hash from two arrays

list1="one two three"
list2="1 2 3"
a = str2list(substr(list1," ",nl))
b = str2list(substr(list2," ",nl))
c = list(len(a))
for i=1 to len(b)
     temp = number(b[i])
     c[temp] = a[i]
next
for i = 1 to len(c)
     see c[i] + " " + i + nl
next


use strict;
use warnings;
use feature 'say';
use Math::AnyNum ':overload';
use List::AllUtils 'firstidx';

my(@H,$n) = 0;
do { ++$n and push @H, $H[-1] + 1/$n } until $H[-1] >= 10;
shift @H;

say 'First twenty harmonic numbers as rationals:';
my $c = 0;
printf("%20s", $_) and (not ++$c%5) and print "\n" for @H[0..19];

say "\nIndex of first value (zero based):";
for my $i (1..10) {
    printf "  greater than %2d: %5s\n", $i, firstidx { $_ > $i } @H;
}


requires("0.8.4")
include mpfr.e
integer n = 1, gn = 1, lim = iff(platform()=JS?8:10)
mpq hn = mpq_init_set_si(1)
sequence gt = {}
puts(1,"First twenty harmonic numbers as rationals:\n")
while gn<=lim do
    if n<=20 then
        printf(1,"%18s%s",{mpq_get_str(hn),iff(mod(n,5)?" ","\n")})
    end if
    if n=100 then
        printf(1,"\nOne Hundredth:\n%s\n\n",{mpq_get_str(hn)})
    end if
    if mpq_cmp_si(hn,gn)>0 then
        gt &= n
        gn += 1
    end if
    n += 1
    mpq_add_si(hn,hn,1,n)
end while
printf(1,"(one based) Index of first value:\n")
for i=1 to length(gt) do
    printf(1,"  greater than %2d: %,6d (%s term)\n",{i,gt[i],ordinal(gt[i])})
end for


func hashJoin<A, B, K: Hashable>(_ first: [(K, A)], _ second: [(K, B)]) -> [(A, K, B)] {
  var map = [K: [B]]()

  for (key, val) in second {
    map[key, default: []].append(val)
  }

  var res = [(A, K, B)]()

  for (key, val) in first {
    guard let vals = map[key] else {
      continue
    }

    res += vals.map({ (val, key, $0) })
  }

  return res
}

let t1 = [
  ("Jonah", 27),
  ("Alan", 18),
  ("Glory", 28),
  ("Popeye", 18),
  ("Alan", 28)
]

let t2 = [
  ("Jonah", "Whales"),
  ("Jonah", "Spiders"),
  ("Alan", "Ghosts"),
  ("Alan", "Zombies"),
  ("Glory", "Buffy")
]

print("Age | Character Name | Nemesis")
print("----|----------------|--------")

for (age, name, nemesis) in hashJoin(t1, t2) {
  print("\(age) | \(name) | \(nemesis)")
}


package require Tcl 8.6
# Only for lmap, which can be replaced with foreach

proc joinTables {tableA a tableB b} {
    # Optimisation: if the first table is longer, do in reverse order
    if {[llength $tableB] < [llength $tableA]} {
	return [lmap pair [joinTables $tableB $b $tableA $a] {
	    lreverse $pair
	}]
    }

    foreach value $tableA {
	lappend hashmap([lindex $value $a]) [lreplace $value $a $a]
	#dict version# dict lappend hashmap [lindex $value $a] [lreplace $value $a $a]
    }
    set result {}
    foreach value $tableB {
	set key [lindex $value $b]
	if {![info exists hashmap($key)]} continue
	#dict version# if {![dict exists $hashmap $key]} continue
	foreach first $hashmap($key) {
	    #dict version# foreach first [dict get $hashmap $key]
	    lappend result [list {*}$first $key {*}[lreplace $value $b $b]]
	}
    }
    return $result
}

set tableA {
    {27 "Jonah"} {18 "Alan"} {28 "Glory"} {18 "Popeye"} {28 "Alan"}
}
set tableB {
    {"Jonah" "Whales"} {"Jonah" "Spiders"} {"Alan" "Ghosts"} {"Alan" "Zombies"}
    {"Glory" "Buffy"}
}
set joined [joinTables $tableA 1 $tableB 0]
foreach row $joined {
    puts $row
}


(defvar age-name '((27 Jonah)
                   (18 Alan)
                   (28 Glory)
                   (18 Popeye)
                   (28 Alan)))

(defvar nemesis-name '((Jonah Whales)
                       (Jonah Spiders)
                       (Alan Ghosts)
                       (Alan Zombies)
                       (Glory Buffy)))

(defun hash-join (left left-key right right-key)
  (let ((join-hash [group-by left-key left])) ;; hash phase
    (append-each ((r-entry right))            ;; join phase
      (collect-each ((l-entry [join-hash [right-key r-entry]]))
        ^(,l-entry ,r-entry)))))

(format t "~s\n" [hash-join age-name second nemesis-name first])


import sun.misc.Signal
import sun.misc.SignalHandler

object SignalHandl extends App {
  val start = System.nanoTime()
  var counter = 0

  Signal.handle(new Signal("INT"), new SignalHandler() {
    def handle(sig: Signal) {
      println(f"\nProgram execution took ${(System.nanoTime() - start) / 1e9f}%f seconds\n")
      exit(0)
    }
  })

  while (true) {
    counter += 1
    println(counter)
    Thread.sleep(500)
  }
}


var start = Time.sec;

Sig.INT { |_|
    Sys.say("Ran for #{Time.sec - start} seconds.");
    Sys.exit;
}

{ |i|
    Sys.say(i);
    Sys.sleep(0.5);
} * Math.inf;


|n|

n := 0.
UserInterrupt
     catch:[
         [true] whileTrue:[
             n := n + 1.
             n printCR.
             Delay waitForSeconds: 0.5.
         ]
     ]


import Foundation

let startTime = NSDate()
var signalReceived: sig_atomic_t = 0

signal(SIGINT) { signal in signalReceived = 1 }

for var i = 0;; {
    if signalReceived == 1 { break }
    usleep(500_000)
    if signalReceived == 1 { break }
    print(++i)
}

let endTime = NSDate()
print("Program has run for \(endTime.timeIntervalSinceDate(startTime)) seconds")


package require Expect

proc sigint_handler {} {
    puts "elapsed time: [expr {[clock seconds] - $::start_time}] seconds"
    set ::looping false
}

trap sigint_handler SIGINT

set start_time [clock seconds]
set n 0
set looping true
while {$looping} {
    puts [incr n]
    after 500
}


show_message("Hello world!"); // displays a pop-up message
show_debug_message("Hello world!"); // sends text to the debug log or IDE


fun sumdigits
                 (0, n) = n
        |        (m, n) = sumdigits (m div 10, m rem 10) + n
        |        n      = sumdigits (n div 10, n rem 10)

fun is_harshad n = (n rem (sumdigits n) = 0)

fun next_harshad_after
		(n, ~1) = if is_harshad n then
			n
		else
			next_harshad_after (n + 1, ~1)
	| 	n = next_harshad_after (n + 1, ~1)

fun harshad
                (max, _, count > max, accum) = rev accum
        |       (max, here, count, accum) =
			if is_harshad here then
                                harshad (max, here + 1, count + 1, here :: accum)
                        else
                                harshad (max, here + 1, count, accum)
        |       max = harshad (max, 1, 1, [])

;

print "first twenty harshad numbers = "; println ` harshad 20;
print "first harshad number after 1000 = "; println ` next_harshad_after 1000;


/* NetRexx ------------------------------------------------------------
* 21.01.2014 Walter Pachl  translated from ooRexx (from REXX version 1)
*--------------------------------------------------------------------*/

options replace format comments java crossref symbols nobinary

  Parse Arg x y .                   /* get optional arguments:  X  Y */
  If x='' Then x=20                 /* Not specified?  Use default   */
  If y='' Then y=1000               /* "      "        "     "       */
  n=0                               /* Niven count                   */
  nl=''                             /* Niven list.                   */

  Loop j=1 By 1 Until n=x           /* let's go Niven number hunting.*/
    If j//sumdigs(j)=0 Then Do      /* j is a Niven number           */
      n=n+1                         /* bump Niven count              */
      nl=nl j                       /* add to list.                  */
      End
    End

  Say 'first' n 'Niven numbers:'nl

  Loop j=y+1 By 1                   /* start with first candidate    */
    If j//sumdigs(j)=0 Then         /* j is a Niven number           */
      Leave
    End

  Say 'first Niven number >' y 'is:' j
  Exit

method sumdigs(n) public static returns Rexx
  sum=n.left(1)
  Loop k=2 To n.length()
    sum=sum+n.substr(k,1)
    End
  Return sum


CrashBandicoot equ $100001
LEA CrashBandicoot,A0
MOVE.W (A0),D0


procedure Halt_And_Catch_Fire is
begin
   raise Program_Error with "Halt and catch fire";
end Halt_And_Catch_Fire;


keys = ['hal',666,[1,2,3]]
vals = ['ibm','devil',123]

hash = Hash[keys.zip(vals)]

p hash  # => {"hal"=>"ibm", 666=>"devil", [1, 2, 3]=>123}

#retrieve the value linked to the key [1,2,3]
puts hash[ [1,2,3] ]  # => 123


use std::collections::HashMap;

fn main() {
    let keys = ["a", "b", "c"];
    let values = [1, 2, 3];

    let hash = keys.iter().zip(values.iter()).collect::<HashMap<_, _>>();
    println!("{:?}", hash);
}


class ZIPPER{K,E} is
  zip(k:ARRAY{K}, e:ARRAY{E}) :MAP{K, E}
    pre k.size = e.size
  is
    m :MAP{K, E} := #;
    loop m[k.elt!] := e.elt!; end;
    return m;
  end;
end;

class MAIN is

  main is
    keys:ARRAY{STR} := |"one", "three", "four"|;
    values:ARRAY{INT} := |1, 3, 4|;
    m ::= ZIPPER{STR,INT}::zip(keys, values);
    loop
      #OUT + m.pair! + " ";
    end;
    #OUT + "\n";
  end;

end;


val keys = List(1, 2, 3)
val values = Array("A", "B", "C") // Array mixed with List
val map = keys.zip(values).toMap  // and other Seq are possible.

// Testing
assert(map == Map(1 ->"A", 2 -> "B", 3 -> "C"))
println("Successfully completed without errors.")


main:-
    print_harmonic_series(20),
    nl,
    nth_harmonic_number(100, T),
    Num is numerator(T),
    Denom is denominator(T),
    writef('100th harmonic number: %t/%t\n', [Num, Denom]),
    nl,
    print_first_harmonic_greater_than(10).

print_harmonic_series(N):-
    writef('First %t harmonic numbers:\n', [N]),
    harmonic_first(H),
    print_harmonic_series(N, H).

print_harmonic_series(N, H):-
    H = h(I, T),
    Num is numerator(T),
    Denom is denominator(T),
    writef('%3r. %t/%t\n', [I, Num, Denom]),
    (I == N, ! ; harmonic_next(H, H1), print_harmonic_series(N, H1)).

print_first_harmonic_greater_than(N):-
    harmonic_first(H),
    print_first_harmonic_greater_than(1, N, H).

print_first_harmonic_greater_than(N, L, _):-
    N > L,
    !.
print_first_harmonic_greater_than(N, L, H):-
    H = h(P, T),
    (T > N ->
        writef('Position of first term >%3r: %t\n', [N, P]),
        N1 is N + 1
        ;
        N1 = N),
    harmonic_next(H, H1),
    print_first_harmonic_greater_than(N1, L, H1).

harmonic_first(h(1, 1)).

harmonic_next(h(N1, T1), h(N2, T2)):-
    N2 is N1 + 1,
    T2 is T1 + 1 rdiv N2.

nth_harmonic_number(N, T):-
    harmonic_first(H),
    nth_harmonic_number(N, T, H).

nth_harmonic_number(N, T, h(N, T)):-!.
nth_harmonic_number(N, T, H1):-
    harmonic_next(H1, H2),
    nth_harmonic_number(N, T, H2).


from  fractions import Fraction

def harmonic_series():
    n, h = Fraction(1), Fraction(1)
    while True:
        yield h
        h += 1 / (n + 1)
        n += 1

if __name__ == '__main__':
    from itertools import islice
    for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)):
        print(n, '/', d)


Dim t_age(4,1)
t_age(0,0) = 27 : t_age(0,1) = "Jonah"
t_age(1,0) = 18 : t_age(1,1) = "Alan"
t_age(2,0) = 28 : t_age(2,1) = "Glory"
t_age(3,0) = 18 : t_age(3,1) = "Popeye"
t_age(4,0) = 28 : t_age(4,1) = "Alan"

Dim t_nemesis(4,1)
t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales"
t_nemesis(1,0) = "Jonah" : t_nemesis(1,1) = "Spiders"
t_nemesis(2,0) = "Alan" : t_nemesis(2,1) = "Ghosts"
t_nemesis(3,0) = "Alan" : t_nemesis(3,1) = "Zombies"
t_nemesis(4,0) = "Glory" : t_nemesis(4,1) = "Buffy"

Call hash_join(t_age,1,t_nemesis,0)

Sub hash_join(table_1,index_1,table_2,index_2)
	Set hash = CreateObject("Scripting.Dictionary")
	For i = 0 To UBound(table_1)
		hash.Add i,Array(table_1(i,0),table_1(i,1))
	Next
	For j = 0 To UBound(table_2)
		For Each key In hash.Keys
			If hash(key)(index_1) = table_2(j,index_2) Then
				WScript.StdOut.WriteLine hash(key)(0) & "," & hash(key)(1) &_
					" = " & table_2(j,0) & "," & table_2(j,1)
			End If
		Next
	Next
End Sub


LOCAL i As Integer, n As Integer
CLOSE DATABASES ALL
*!* Create and populate the hash tables
CREATE CURSOR people_ids(id I, used L DEFAULT .F.)
INDEX ON id TAG id COLLATE "Machine"
INDEX ON used TAG used BINARY COLLATE "Machine"
SET ORDER TO 0
CREATE CURSOR nem_ids(id I, used L DEFAULT .F.)
INDEX ON id TAG id COLLATE "Machine"
INDEX ON used TAG used BINARY COLLATE "Machine"
SET ORDER TO 0
n = 100
FOR i = 1 TO n
    INSERT INTO people_ids (id) VALUES (i)
    INSERT INTO nem_ids (id) VALUES (i)
ENDFOR

CREATE CURSOR people (age I, name V(16), id I)
INDEX ON id TAG id COLLATE "Machine"
INDEX ON name TAG name COLLATE "Machine"
SET ORDER TO 0
INSERT INTO people (age, name) VALUES (27, "Jonah")
INSERT INTO people (age, name) VALUES (18, "Alan")
INSERT INTO people (age, name) VALUES (28, "Glory")
INSERT INTO people (age, name) VALUES (18, "Popeye")
INSERT INTO people (age, name) VALUES (28, "Alan")
REPLACE id WITH HashMe("people_ids") ALL

*!* The plural of nemesis is nemeses
CREATE CURSOR nemeses (name V(16), nemesis V(16), p_id I, id I)
INDEX ON id TAG id COLLATE "Machine"
INDEX ON p_id TAG p_id COLLATE "Machine"
INDEX ON name TAG name COLLATE "Machine"
SET ORDER TO 0

INSERT INTO nemeses (name, nemesis) VALUES ("Jonah", "Whales")
INSERT INTO nemeses (name, nemesis) VALUES ("Jonah", "Spiders")
INSERT INTO nemeses (name, nemesis) VALUES ("Alan", "Ghosts")
INSERT INTO nemeses (name, nemesis) VALUES ("Alan", "Zombies")
INSERT INTO nemeses (name, nemesis) VALUES ("Glory", "Buffy")
REPLACE id WITH HashMe("nem_ids") ALL
UPDATE nemeses SET p_id = people.id FROM people ;
WHERE nemeses.name = people.name

*!* Show the join
SELECT pe.age, pe.name, ne.nemesis FROM people pe ;
JOIN nemeses ne ON pe.id = ne.p_id TO FILE "hashjoin.txt"

FUNCTION HashMe(cTable As String) As Integer
LOCAL ARRAY a[1]
SELECT MIN(id) FROM (cTable) WHERE NOT used INTO ARRAY a
UPDATE (cTable) SET used = .T. WHERE id = a[1]
RETURN a[1]
ENDFUNC


import "/fmt" for Fmt

class A {
    construct new(age, name) {
        _age = age
        _name = name
    }

    age  { _age  }
    name { _name }
}

class B {
    construct new(character, nemesis) {
        _character = character
        _nemesis = nemesis
    }

    character { _character }
    nemesis   { _nemesis   }
}

var tableA = [
    A.new(27, "Jonah"),  A.new(18, "Alan"), A.new(28, "Glory"),
    A.new(18, "Popeye"), A.new(28, "Alan")
]
var tableB = [
    B.new("Jonah", "Whales"), B.new("Jonah", "Spiders"), B.new("Alan", "Ghosts"),
    B.new("Alan", "Zombies"), B.new("Glory", "Buffy")
]
var h = {}
var i = 0
for (a in tableA) {
    var n = h[a.name]
    if (n) {
        n.add(i)
    } else {
        h[a.name] = [i]
    }
    i = i + 1
}

System.print("Age  Name   Character Nemesis")
System.print("---  -----  --------- -------")
for (b in tableB) {
    var c = h[b.character]
    if (c) {
        for (i in c) {
            var t = tableA[i]
            Fmt.print("$3d  $-5s  $-9s $s", t.age, t.name, b.character, b.nemesis)
        }
    }
}