0000                                 .model  tiny
0000                                 .code
                                     .486
                                     org     100h            ;.com files start here
0100  9B DB E3               start:  finit                   ;initialize floating-point unit (FPU)
                             ;Great circle distance =
                             ; 2.0*Radius * ASin( sqrt( Haversine(Lat2-Lat1) +
                             ;                          Haversine(Lon2-Lon1)*Cos(Lat1)*Cos(Lat2) ) )
0103  D9 06 0191r                    fld     Lat2            ;push real onto FPU stack
0107  D8 26 018Dr                    fsub    Lat1            ;subtract real from top of stack (st(0) = st)
010B  E8 0070                        call    Haversine       ;(1.0-cos(st)) / 2.0
010E  D9 06 0199r                    fld     Lon2            ;repeat for longitudes
0112  D8 26 0195r                    fsub    Lon1
0116  E8 0065                        call    Haversine       ;st(1)=Lats; st=Lons
0119  D9 06 018Dr                    fld     Lat1
011D  D9 FF                          fcos                    ;replace st with its cosine
011F  D9 06 0191r                    fld     Lat2
0123  D9 FF                          fcos            ;st=cos(Lat2); st(1)=cos(Lat1); st(2)=Lats; st(3)=Lons
0125  DE C9                          fmul            ;st=cos(Lat2)*cos(Lat1); st(1)=Lats; st(2)=Lons
0127  DE C9                          fmul            ;st=cos(Lat2)*cos(Lat1)*Lats; st(1)=Lons
0129  DE C1                          fadd            ;st=cos(Lat2)*cos(Lat1)*Lats + Lons
012B  D9 FA                          fsqrt                   ;replace st with its square root
                             ;asin(x) = atan(x/sqrt(1-x^2))
012D  D9 C0                          fld     st              ;duplicate tos
012F  D8 C8                          fmul    st, st          ;x^2
0131  D9 E8                          fld1                    ;get 1.0
0133  DE E1                          fsubr                   ;1 - x^2
0135  D9 FA                          fsqrt                   ;sqrt(1-x^2)
0137  D9 F3                          fpatan                  ;take atan(st(1)/st)
0139  D8 0E 019Dr                    fmul    Radius2         ;*2.0*Radius

                             ;Display value in FPU's top of stack (st)
      =0004                  before  equ     4               ;places before
      =0002                  after   equ     2               ; and after decimal point
      =0001                  scaler  =       1               ;"=" allows scaler to be redefined, unlike equ
                                     rept    after           ;repeat block "after" times
                             scaler  =       scaler*10
                                     endm                    ;scaler now = 10^after

013D  66| 6A 64                      push    dword ptr scaler;use stack for convenient memory location
0140  67| DA 0C 24                   fimul   dword ptr [esp] ;st:= st*scaler
0144  67| DB 1C 24                   fistp   dword ptr [esp] ;round st to nearest integer
0148  66| 58                         pop     eax             ; and put it into eax

014A  66| BB 0000000A                mov     ebx, 10         ;set up for idiv instruction
0150  B9 0006                        mov     cx, before+after;set up loop counter
0153  66| 99                 ro10:   cdq                     ;convert double to quad; i.e: edx:= 0
0155  66| F7 FB                      idiv    ebx             ;eax:= edx:eax/ebx; remainder in edx
0158  52                             push    dx              ;save least significant digit on stack
0159  E2 F8                          loop    ro10            ;cx--; loop back if not zero

015B  B1 06                          mov     cl, before+after;(ch=0)
015D  B3 00                          mov     bl, 0           ;used to suppress leading zeros
015F  58                     ro20:   pop     ax              ;get digit
0160  0A D8                          or      bl, al          ;turn off suppression if not a zero
0162  80 F9 03                       cmp     cl, after+1     ;is digit immediately to left of decimal point?
0165  75 01                          jne     ro30            ;skip if not
0167  43                              inc    bx              ;turn off leading zero suppression
0168  04 30                  ro30:   add     al, '0'         ;if leading zero then ' ' else add 0
016A  84 DB                          test    bl, bl
016C  75 02                          jne     ro40
016E  B0 20                           mov    al, ' '
0170  CD 29                  ro40:   int     29h             ;display character in al register
0172  80 F9 03                       cmp     cl, after+1     ;is digit immediately to left of decimal point?
0175  75 04                          jne     ro50            ;skip if not
0177  B0 2E                           mov    al, '.'         ;display decimal point
0179  CD 29                           int    29h
017B  E2 E2                  ro50:   loop    ro20            ;loop until all digits displayed
017D  C3                             ret                     ;return to OS

017E                         Haversine:                      ;return (1.0-Cos(Ang)) / 2.0 in st
017E  D9 FF                          fcos
0180  D9 E8                          fld1
0182  DE E1                          fsubr
0184  D8 36 0189r                    fdiv    N2
0188  C3                             ret

0189  40000000               N2      dd       2.0
018D  3F21628D               Lat1    dd       0.63041        ;36.12*pi/180
0191  3F17A4E8               Lat2    dd       0.59236        ;33.94*pi/180
0195  BFC19F80               Lon1    dd      -1.51268        ;-86.67*pi/180
0199  C004410B               Lon2    dd      -2.06647        ;-118.40*pi/180
019D  46472666               Radius2 dd      12745.6         ;6372.8 average radius of Earth (km) times 2
                             ;(TASM isn't smart enough to do floating point constant calculations)
                                     end     start


function happy(number) {
    var m, digit ;
    var cycle = [] ;

    while(number != 1 && cycle[number] !== true) {
        cycle[number] = true ;
        m = 0 ;
        while (number > 0) {
            digit = number % 10 ;
            m += digit * digit ;
            number = (number  - digit) / 10 ;
        }
        number = m ;
    }
    return (number == 1) ;
}

var cnt = 8 ;
var number = 1 ;

while(cnt-- > 0) {
    while(!happy(number))
        number++ ;
    document.write(number + " ") ;
    number++ ;
}


def is_happy_number:
  def next: tostring | explode | map( (. - 48) | .*.) | add;
  def last(g): reduce g as $i (null; $i);
  # state: either 1 or [i, o]
  # where o is an an object with the previously encountered numbers as keys
  def loop:
   recurse( if      . == 1 then empty    # all done
            elif .[0] == 1 then 1        # emit 1
            else (.[0]| next) as $n
            | if $n == 1 then 1
              elif .[1]|has($n|tostring) then empty
              else [$n, (.[1] + {($n|tostring):true}) ]
              end
            end );
  1 == last( [.,{}] | loop );


void main(){
	stdout.printf("Hello world!\n");
}


desc:  .ascid "Hello World!"      ;descriptor (len+addr) and text
.entry hello, ^m<>                ;register save mask
       pushaq desc                ;address of descriptor
       calls #1, g^lib$put_output ;call with one argument on stack
       ret                        ;restore registers, clean stack & return
.end hello                        ;transfer address for linker


Public Sub hello_world_text
    Debug.Print "Hello World!"
End Sub


include c:\cxpl\codes;                  \intrinsic 'code' declarations

func real Haversine(Ang);
real Ang;
return (1.0-Cos(Ang)) / 2.0;

func real Dist(Lat1, Lat2, Lon1, Lon2); \Great circle distance
real Lat1, Lat2, Lon1, Lon2;
def R = 6372.8;                         \average radius of Earth (km)
return 2.0*R * ASin( sqrt( Haversine(Lat2-Lat1) +
       Cos(Lat1)*Cos(Lat2)*Haversine(Lon2-Lon1) ));

def D2R = 3.141592654/180.0;            \degrees to radians
RlOut(0, Dist(36.12*D2R, 33.94*D2R, -86.67*D2R, -118.40*D2R ));


declare namespace xsd = "http://www.w3.org/2001/XMLSchema";
declare namespace math = "http://www.w3.org/2005/xpath-functions/math";

declare function local:haversine($lat1 as xsd:float, $lon1 as xsd:float, $lat2 as xsd:float, $lon2 as xsd:float)
    as xsd:float
{
    let $dlat  := ($lat2 - $lat1) * math:pi() div 180
    let $dlon  := ($lon2 - $lon1) * math:pi() div 180
    let $rlat1 := $lat1 * math:pi() div 180
    let $rlat2 := $lat2 * math:pi() div 180
    let $a     := math:sin($dlat div 2) * math:sin($dlat div 2) + math:sin($dlon div 2) * math:sin($dlon div 2) * math:cos($rlat1) * math:cos($rlat2)
    let $c     := 2 * math:atan2(math:sqrt($a), math:sqrt(1-$a))
    return xsd:float($c * 6371.0)
};

local:haversine(36.12, -86.67, 33.94, -118.4)


//pi está predefinido en Yabasic
deg2rad = pi / 180    // define grados a radianes 0.01745..
radioTierra = 6372.8  // radio de la tierra en km

sub Haversine(lat1, long1, lat2, long2 , radio)
    d_long = deg2rad * (long1 - long2)
    theta1 = deg2rad * lat1
    theta2 = deg2rad * lat2
    dx = cos(d_long) * cos(theta1) - cos(theta2)
    dy = sin(d_long) * cos(theta1)
    dz = sin(theta1) - sin(theta2)
    return asin(sqr(dx*dx + dy*dy + dz*dz) / 2) * radio * 2
end sub

print " Distancia de Haversine entre BNA y LAX = ", Haversine(36.12, -86.67, 33.94, -118.4, radioTierra), " km"
end


haversine(36.12, -86.67, 33.94, -118.40).println();

fcn haversine(Lat1, Long1, Lat2, Long2){
   const R = 6372.8; 	// In kilometers;
   Diff_Lat  := (Lat2  - Lat1) .toRad();
   Diff_Long := (Long2 - Long1).toRad();
   NLat      := Lat1.toRad();
   NLong     := Lat2.toRad();
   A 	     := (Diff_Lat/2) .sin().pow(2) +
                (Diff_Long/2).sin().pow(2) *
		NLat.cos() * NLong.cos();
   C 	     := 2.0 * A.sqrt().asin();
   R*C;
}


10 LET diam=2*6372.8
20 LET Lg1m2=FN r((-86.67)-(-118.4))
30 LET Lt1=FN r(36.12)
40 LET Lt2=FN r(33.94)
50 LET dz=SIN (Lt1)-SIN (Lt2)
60 LET dx=COS (Lg1m2)*COS (Lt1)-COS (Lt2)
70 LET dy=SIN (Lg1m2)*COS (Lt1)
80 LET hDist=ASN ((dx*dx+dy*dy+dz*dz)^0.5/2)*diam
90 PRINT "Haversine distance: ";hDist;" km."
100 STOP
1000 DEF FN r(a)=a*0.017453293: REM convert degree to radians


function happy(x)
	happy_ints = ref(Int)
	int_try = 1
	while length(happy_ints) < x
		n = int_try
		past = ref(Int)
		while n != 1
	        	n = sum([y^2 for y in digits(n)])
	        	contains(past,n) ? break : push!(past,n)
	    	end
		n == 1 && push!(happy_ints,int_try)
		int_try += 1
	end
	return happy_ints
end


// version 1.0.5-2

fun isHappy(n: Int): Boolean {
    val cache = mutableListOf<Int>()
    var sum = 0
    var nn = n
    var digit: Int
    while (nn != 1) {
        if (nn in cache) return false
        cache.add(nn)
        while (nn != 0) {
            digit = nn % 10
            sum += digit * digit
            nn /= 10
        }
        nn = sum
        sum = 0
    }
    return true
}

fun main(args: Array<String>) {
    var num = 1
    val happyNums = mutableListOf<Int>()
    while (happyNums.size < 8) {
        if (isHappy(num)) happyNums.add(num)
        num++
    }
    println("First 8 happy numbers : " + happyNums.joinToString(", "))
}


module main;
  initial begin
      $display("Hello world!");
      $finish ;
    end
endmodule


#!/usr/bin/lasso9

define isHappy(n::integer) => {
  local(past = set)
  while(#n != 1) => {
    #n = with i in string(#n)->values sum math_pow(integer(#i), 2)
    #past->contains(#n) ? return false | #past->insert(#n)
  }
  return true
}

with x in generateSeries(1, 500)
  where isHappy(#x)
  take 8
select #x


    ct = 0
    n = 0
    DO
        n = n + 1
        IF HappyN(n, sqrInt$) = 1 THEN
            ct = ct + 1
            PRINT ct, n
        END IF
    LOOP UNTIL ct = 8
END

FUNCTION HappyN(n, sqrInts$)
    n$ = Str$(n)
    sqrInts = 0
    FOR i = 1 TO Len(n$)
        sqrInts = sqrInts + Val(Mid$(n$, i, 1)) ^ 2
    NEXT i
    IF sqrInts = 1 THEN
        HappyN = 1
        EXIT FUNCTION
    END IF
    IF Instr(sqrInts$, ":";Str$(sqrInts);":") > 0 THEN
        HappyN = 0
        EXIT FUNCTION
    END IF
    sqrInts$ = sqrInts$ + Str$(sqrInts) + ":"
    HappyN = HappyN(sqrInts, sqrInts$)
END FUNCTION


LIBRARY std;
USE std.TEXTIO.all;

entity test is
end entity test;

architecture beh of test is
begin
  process
    variable line_out : line;
  begin
    write(line_out, string'("Hello world!"));
    writeline(OUTPUT, line_out);
    wait; -- needed to stop the execution
  end process;
end architecture beh;


Option Explicit

Private Declare Function AllocConsole Lib "kernel32.dll" () As Long
Private Declare Function FreeConsole Lib "kernel32.dll" () As Long
'needs a reference set to "Microsoft Scripting Runtime" (scrrun.dll)

Sub Main()
  Call AllocConsole
  Dim mFSO As Scripting.FileSystemObject
  Dim mStdIn As Scripting.TextStream
  Dim mStdOut As Scripting.TextStream
  Set mFSO = New Scripting.FileSystemObject
  Set mStdIn = mFSO.GetStandardStream(StdIn)
  Set mStdOut = mFSO.GetStandardStream(StdOut)
  mStdOut.Write "Hello world!" & vbNewLine
  mStdOut.Write "press enter to quit program."
  mStdIn.Read 1
  Call FreeConsole
End Sub


10 mode 1:defint a-z
20 for i=1 to 100
30 i2=i
40 for l=1 to 20
50 a$=str$(i2)
60 i2=0
70 for j=1 to len(a$)
80 d=val(mid$(a$,j,1))
90 i2=i2+d*d
100 next j
110 if i2=1 then print i;"is a happy number":n=n+1:goto 150
120 if i2=4 then 150 ' cycle found
130 next l
140 ' check if we have reached 8 numbers yet
150 if n=8 then end
160 next i


to sum_of_square_digits :number
  output (apply "sum (map [[d] d*d] ` :number))
end

to is_happy? :number [:seen []]
  output cond [
    [ [:number = 1] "true ]
    [ [member? :number :seen] "false ]
    [ else (is_happy? (sum_of_square_digits :number) (lput :number :seen))]
  ]
end

to n_happy :count [:start 1] [:result []]
  output cond [
    [ [:count <= 0] :result ]
    [ [is_happy? :start]
      (n_happy (:count-1) (:start+1) (lput :start :result)) ]
    [ else
      (n_happy :count (:start+1) :result) ]
  ]
end

print n_happy 8
bye


Imports System

Module HelloWorld
    Sub Main()
        Console.WriteLine("Hello world!")
    End Sub
End Module


.function: main/0
    text %1 local "Hello World!"
    print %1 local
    izero %0 local
    return
.end


fn main() {
        println('Hello World!')
}


OBTW
  Happy Numbers Rosetta Code task in LOLCODE
  Requires 1.3 for BUKKIT availability
TLDR
HAI 1.3
CAN HAS STDIO?

BTW Simple list implementation.
BTW Used for the list of numbers already seen in IZHAPPY

BTW Create a list
HOW IZ I MAEKLIST
  I HAS A LIST ITZ A BUKKIT
  LIST HAS A LENGTH ITZ 0
  FOUND YR LIST
IF U SAY SO

BTW Append an item to list
HOW IZ I PUTIN YR LIST AN YR ITEM
  LIST HAS A SRS LIST'Z LENGTH ITZ ITEM
  LIST'Z LENGTH R SUM OF LIST'Z LENGTH AN 1
IF U SAY SO

BTW Check for presence of an item in the list
HOW IZ I DUZLISTHAS YR HAYSTACK AN YR NEEDLE
  IM IN YR BARN UPPIN YR INDEX WILE DIFFRINT INDEX AN HAYSTACK'Z LENGTH
    I HAS A ITEM ITZ HAYSTACK'Z SRS INDEX
    BOTH SAEM ITEM AN NEEDLE
    O RLY?
      YA RLY
        FOUND YR WIN
    OIC
  IM OUTTA YR BARN
  FOUND YR FAIL
IF U SAY SO

BTW Calculate the next number using the happy formula
HOW IZ I HAPPYSTEP YR NUM
  I HAS A NEXT ITZ 0
  IM IN YR LOOP
    BOTH SAEM NUM AN 0
    O RLY?
      YA RLY
        GTFO
    OIC
    I HAS A DIGIT ITZ MOD OF NUM AN 10
    NUM R QUOSHUNT OF NUM AN 10
    I HAS A SQUARE ITZ PRODUKT OF DIGIT AN DIGIT
    NEXT R SUM OF NEXT AN SQUARE
  IM OUTTA YR LOOP
  FOUND YR NEXT
IF U SAY SO

BTW Check to see if a number is happy
HOW IZ I IZHAPPY YR NUM
  I HAS A SEENIT ITZ I IZ MAEKLIST MKAY
  IM IN YR LOOP
    BOTH SAEM NUM AN 1
    O RLY?
      YA RLY
        FOUND YR WIN
    OIC
    I IZ DUZLISTHAS YR SEENIT AN YR NUM MKAY
    O RLY?
      YA RLY
        FOUND YR FAIL
    OIC
    I IZ PUTIN YR SEENIT AN YR NUM MKAY
    NUM R I IZ HAPPYSTEP YR NUM MKAY
  IM OUTTA YR LOOP
IF U SAY SO

BTW Print out the first 8 happy numbers
I HAS A KOUNT ITZ 0
IM IN YR LOOP UPPIN YR NUM WILE DIFFRINT KOUNT AN 8
  I IZ IZHAPPY YR NUM MKAY
  O RLY?
    YA RLY
      KOUNT R SUM OF KOUNT AN 1
      VISIBLE NUM
  OIC
IM OUTTA YR LOOP
KTHXBYE


(module $helloworld

    ;;Import fd_write from WASI, declaring that it takes 4 i32 inputs and returns 1 i32 value
    (import "wasi_unstable" "fd_write"
        (func $fd_write (param i32 i32 i32 i32) (result i32))
    )

    ;;Declare initial memory size of 32 bytes
    (memory 32)

    ;;Export memory so external functions can see it
    (export "memory" (memory 0))

    ;;Declare test data starting at address 8
    (data (i32.const 8) "Hello world!\n")

    ;;The entry point for WASI is called _start
    (func $main (export "_start")

        ;;Write the start address of the string to address 0
        (i32.store (i32.const 0) (i32.const 8))

        ;;Write the length of the string to address 4
        (i32.store (i32.const 4) (i32.const 13))

        ;;Call fd_write to print to console
        (call $fd_write
            (i32.const 1) ;;Value of 1 corresponds to stdout
            (i32.const 0) ;;The location in memory of the string pointer
            (i32.const 1) ;;Number of strings to output
            (i32.const 24) ;;Address to write number of bytes written
        )
        drop ;;Ignore return code
    )
)


function digits(n)
  if n > 0 then return n % 10, digits(math.floor(n/10)) end
end
function sumsq(a, ...)
  return a and a ^ 2 + sumsq(...) or 0
end
local happy = setmetatable({true, false, false, false}, {
      __index = function(self, n)
         self[n] = self[sumsq(digits(n))]
         return self[n]
      end } )
i, j = 0, 1
repeat
   i, j = happy[j] and (print(j) or i+1) or i, j + 1
until i == 8


Function FactoryHappy {
      sumOfSquares= lambda (n) ->{
                  k$=str$(abs(n),"")
                  Sum=0
                  For i=1 to len(k$)
                        sum+=val(mid$(k$,i,1))**2
                  Next i
                  =sum
      }
      IsHappy=Lambda sumOfSquares (n) ->{
            Inventory sequence
            While n<>1 {
                  Append sequence, n
                  n=sumOfSquares(n)
                   if exist(sequence, n) then =false : Break
            }
            =True
      }
      =Lambda IsHappy ->{
                  numleft=8
                  numToTest=1
                  While numleft {
                        if ishappy(numToTest) Then {
                              Print numToTest
                              numleft--
                        }
                        numToTest++
                  }
      }
}
PrintHappy=factoryHappy()
Call PrintHappy()


import whiley.lang.System

method main(System.Console console):
    console.out.println("Hello world!")


import : scheme base
         scheme write
display "Hello world!"
newline


            NORMAL MODE IS INTEGER
            BOOLEAN CYCLE
            DIMENSION CYCLE(200)
            VECTOR VALUES OUTFMT = $I2*$

            SEEN = 0
            I = 0

NEXNUM      THROUGH ZERO, FOR K=0, 1, K.G.200
ZERO        CYCLE(K) = 0B
            I = I + 1
            SUMSQR = I
CHKLP       N = SUMSQR
            SUMSQR = 0
SUMLP       DIG = N-N/10*10
            SUMSQR = SUMSQR + DIG*DIG
            N = N/10
            WHENEVER N.NE.0, TRANSFER TO SUMLP
            WHENEVER SUMSQR.E.1, TRANSFER TO HAPPY
            WHENEVER CYCLE(SUMSQR), TRANSFER TO NEXNUM
            CYCLE(SUMSQR) = 1B
            TRANSFER TO CHKLP

HAPPY       PRINT FORMAT OUTFMT,I
            SEEN = SEEN+1
            WHENEVER SEEN.L.8, TRANSFER TO NEXNUM

            END OF PROGRAM


SumSqDigits := proc( n :: posint )
        local s := 0;
        local m := n;
        while m <> 0 do
                s := s + irem( m, 10, 'm' )^2
        end do;
        s
end proc:


class HelloWorld {
  public static def main(args:Rail[String]):void {
    if (args.size < 1) {
        Console.OUT.println("Hello world!");
        return;
    }
  }
}


section .data
msg     db      'Hello world!', 0AH
len     equ     $-msg

section .text
global  _start
_start: mov     edx, len
        mov     ecx, msg
        mov     ebx, 1
        mov     eax, 4
        int     80h

        mov     ebx, 0
        mov     eax, 1
        int     80h


function findHappyNumbers
    nHappy = 0;
    k = 1;
    while nHappy < 8
        if isHappyNumber(k, [])
            fprintf('%d ', k)
            nHappy = nHappy+1;
        end
        k = k+1;
    end
    fprintf('\n')
end

function hap = isHappyNumber(k, prev)
    if k == 1
        hap = true;
    elseif ismember(k, prev)
        hap = false;
    else
        hap = isHappyNumber(sum((sprintf('%d', k)-'0').^2), [prev k]);
    end
end


fn isHappyNumber n =
(
	local pastNumbers = #()
	while n != 1 do
	(
		n = n as string
		local newNumber = 0
		for i = 1 to n.count do
		(
			local digit = n[i] as integer
			newNumber += pow digit 2
		)
		n = newNumber
		if (finditem pastNumbers n) != 0 do return false
		append pastNumbers newNumber
	)
	n == 1
)
printed = 0
for i in (for h in 1 to 500 where isHappyNumber h collect h) do
(
	if printed == 8 do exit
	print i as string
	printed += 1

)


option casemap:none
if @Platform eq 1
   option dllimport:<kernel32>
      ExitProcess   proto :dword
   option dllimport:none
      exit          equ ExitProcess
endif
printf              proto :qword, :vararg
exit                proto :dword

.code
main proc
invoke printf, CSTR("Goodbye, World!",10)
invoke exit, 0
ret
main endp
end


PROGRAM "hello"
VERSION "0.0003"

DECLARE FUNCTION Entry()

FUNCTION Entry()
  PRINT "Hello World"
END FUNCTION
END PROGRAM


h#10 h$! h$d h$l h$r h$o h$w h#32
h$o h$l h$l h$e h$H >o o$ p jno


:- module happy.
:- interface.
:- import_module io.

:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module int, list, set_tree234.

main(!IO) :-
    print_line(get_n_happy_numbers(8, 1), !IO).

:- func get_n_happy_numbers(int, int) = list(int).

get_n_happy_numbers(NumToFind, N) =
    ( if NumToFind > 0 then
       ( if is_happy(N, init)
       then [N | get_n_happy_numbers(NumToFind - 1, N + 1)]
       else get_n_happy_numbers(NumToFind, N + 1)
       )
    else
       []
    ).

:- pred is_happy(int::in, set_tree234(int)::in) is semidet.

is_happy(1, _).
is_happy(N, !.Seen) :-
   not member(N, !.Seen),
   insert(N, !Seen),
   is_happy(sum_sqr_digits(N), !.Seen).

:- func sum_sqr_digits(int) = int.

sum_sqr_digits(N) =
   ( if N < 10 then sqr(N) else sqr(N mod 10) + sum_sqr_digits(N div 10) ).

:- func sqr(int) = int.

sqr(X) = X * X.


isHappy = function(x)
    while true
        if x == 89 then return false
        sum = 0
        while x > 0
            sum = sum + (x % 10)^2
            x = floor(x / 10)
        end while
        if sum == 1 then return true
        x = sum
    end while
end function

found = []
i = 1
while found.len < 8
    if isHappy(i) then found.push i
    i = i + 1
end while
print "First 8 happy numbers: " + found


(*
A happy number is defined by the following process. Starting with any positive integer, replace the number
by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will
stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends
 in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. Display an example of your
output here.
*)

local
	fun get_digits
			(d, s) where (d = 0) = s
		| 	(d, s) = get_digits( d div 10, (d mod 10) :: s)
		| 	n = get_digits( n div 10, [n mod 10] )
	;
	fun mem
			(x, []) = false
		| 	(x, a :: as) where (x = a) = true
		| 	(x, _ :: as) = mem (x, as)
in
	fun happy
			1 = "happy"
		|	n =
				let
					val this = (fold (+,0) ` map (fn n = n ^ 2) ` get_digits n);
					val sads = [2, 4, 16, 37, 58, 89, 145, 42, 20]
				in
					if (mem (n,sads)) then
						"unhappy"
					else
						happy this
				end
end
;

foreach (fn n = (print n; print " is "; println ` happy n)) ` iota 10;


use XL.UI.CONSOLE
WriteLn "Hello world!"


MODULE HappyNumbers;
FROM InOut IMPORT WriteCard, WriteLn;

CONST Amount = 8;
VAR seen, num: CARDINAL;

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

PROCEDURE Happy(n: CARDINAL): BOOLEAN;
VAR i: CARDINAL;
    seen: ARRAY [0..255] OF BOOLEAN;
BEGIN
    FOR i := 0 TO 255 DO
        seen[i] := FALSE;
    END;
    REPEAT
        seen[n] := TRUE;
        n := SumDigitSquares(n);
    UNTIL seen[n];
    RETURN seen[1];
END Happy;

BEGIN
    seen := 0;
    num := 0;
    WHILE seen < Amount DO
        IF Happy(num) THEN
            INC(seen);
            WriteCard(num,2);
            WriteLn();
        END;
        INC(num);
    END;
END HappyNumbers.


ISHAPPY(N)
 ;Determines if a number N is a happy number
 ;Note that the returned strings do not have a leading digit unless it is a happy number
 IF (N'=N\1)!(N<0) QUIT "Not a positive integer"
 NEW SUM,I
 ;SUM is the sum of the square of each digit
 ;I is a loop variable
 ;SEQ is the sequence of previously checked SUMs from the original N
 ;If it isn't set already, initialize it to an empty string
 IF $DATA(SEQ)=0 NEW SEQ SET SEQ=""
 SET SUM=0
 FOR I=1:1:$LENGTH(N) DO
 .SET SUM=SUM+($EXTRACT(N,I)*$EXTRACT(N,I))
 QUIT:(SUM=1) SUM
 QUIT:$FIND(SEQ,SUM)>1 "Part of a sequence not containing 1"
 SET SEQ=SEQ_","_SUM
 QUIT $$ISHAPPY(SUM)
HAPPY(C) ;Finds the first C happy numbers
 NEW I
 ;I is a counter for what integer we're looking at
 WRITE !,"The first "_C_" happy numbers are:"
 FOR I=1:1 QUIT:C<1  SET Q=+$$ISHAPPY(I) WRITE:Q !,I SET:Q C=C-1
 KILL I
 QUIT


/*NetRexx program to display the 1st 8 (or specified arg) happy numbers*/
limit	 = arg[0]                        /*get argument for  LIMIT.        */
say limit
if limit = null, limit ='' then limit=8  /*if not specified, set LIMIT to 8*/
haps	 = 0                             /*count of happy numbers so far.  */

loop n=1 while haps < limit              /*search integers starting at one.*/
  q=n                                    /*Q may or may not be "happy".    */
  a=0

  loop forever                           /*see if  Q  is a happy number.   */
    if q==1 then do                      /*if  Q  is unity, then it's happy*/
      haps = haps + 1                    /*bump the count of happy numbers.*/
      say n                              /*display the number.             */
      iterate n                          /*and then keep looking for more. */
    end

    sum=0                                /*initialize sum to zero.         */

    loop j=1 for q.length                /*add the squares of the numerals.*/
      sum = sum + q.substr(j,1) ** 2
    end

    if a[sum] then iterate n             /*if already summed, Q is unhappy.*/
    a[sum]=1                             /*mark the sum as being found.    */
    q=sum                                /*now, lets try the  Q  sum.      */
  end
end


import intsets

proc happy(n: int): bool =
  var
    n = n
    past = initIntSet()
  while n != 1:
    let s = $n
    n = 0
    for c in s:
      let i = ord(c) - ord('0')
      n += i * i
    if n in past:
      return false
    past.incl(n)
  return true

for x in 0..31:
  if happy(x):
    echo x


org		$4000

txt_output:	equ	$bb5a

		push	hl
		ld	hl,world

print:		ld	a,(hl)
		cp	0
		jr	z,end
		call	txt_output
		inc	hl
		jr	print

end:		pop	hl
		ret

world:		defm	"Hello world!\r\n\0"


const std = @import("std");
pub fn main() !void {
    try std.io.getStdOut().writer().writeAll("Hello world!\n");
}


use IO;
use Structure;

bundle Default {
  class HappyNumbers {
    function : native : IsHappy(n : Int) ~ Bool {
      cache := IntVector->New();
        sum := 0;
        while(n <> 1) {
          if(cache->Has(n)) {
            return false;
          };

          cache->AddBack(n);
          while(n <> 0) {
            digit := n % 10;
            sum += (digit * digit);
            n /= 10;
          };

          n := sum;
          sum := 0;
        };

        return true;
      }

      function : Main(args : String[]) ~ Nil {
        num := 1;
        happynums := IntVector->New();

        while(happynums->Size() < 8) {
          if(IsHappy(num)) {
            happynums->AddBack(num);
        };

        num += 1;
      };

      Console->Print("First 8 happy numbers: ");
      each(i : happynums) {
        Console->Print(happynums->Get(i))->Print(",");
      };
      Console->PrintLine("");
    }
  }
}


program: hello_world
  output: "Hello  world!"


open Num

let step =
	let rec aux s n =
	if n =/ Int 0 then s else
		let q = quo_num n (Int 10)
		and r = mod_num n (Int 10)
		in aux (s +/ (r */ r)) q
	in aux (Int 0) ;;

let happy n =
	let rec aux x y =
		if x =/ y then x else aux (step x) (step (step y))
	in (aux n (step n)) =/ Int 1 ;;

let first n =
	let rec aux v x n =
		if n = 0 then v else
			if happy x
			then aux (x::v) (x +/ Int 1) (n - 1)
			else aux v (x +/ Int 1) n
	in aux [ ] (Int 1) n ;;

List.iter print_endline (
	List.rev_map string_of_num (first 8)) ;;


: isHappy(n)
| cycle |
   ListBuffer new ->cycle

   while(n 1 <>) [
      cycle include(n) ifTrue: [ false return ]
      cycle add(n)
      0 n asString apply(#[ asDigit sq + ]) ->n
      ]
   true ;

: happyNum(N)
| numbers |
   ListBuffer new ->numbers
   1 while(numbers size N <>) [ dup isHappy ifTrue: [ dup numbers add ] 1+ ]
   numbers println ;


count = 0
say "First 8 happy numbers are:"
loop i = 1 while count < 8
    if happyNumber(i) then do
        count += 1
        say i
    end
end

::routine happyNumber
  use strict arg number

  -- use to trace previous cycle results
  previous = .set~new
  loop forever
      -- stop when we hit the target
      if number = 1 then return .true
      -- stop as soon as we start cycling
      if previous[number] \== .nil then return .false
      previous~put(number)
      next = 0
      -- loop over all of the digits
      loop digit over number~makearray('')
          next += digit * digit
      end
      -- and repeat the cycle
      number = next
  end


functor
import
  System
define
  fun {IsHappy N}
     {IsHappy2 N nil}
  end

  fun {IsHappy2 N Seen}
     if     N == 1          then true
     elseif {Member N Seen} then false
     else
	Next = {Sum {Map {Digits N} Square}}
     in
	{IsHappy2 Next N|Seen}
     end
  end

  fun {Sum Xs}
     {FoldL Xs Number.'+' 0}
  end

  fun {Digits N}
     {Map {Int.toString N} fun {$ D} D - &0 end}
  end

  fun {Square N} N*N end

  fun lazy {Nat I}
     I|{Nat I+1}
  end

  %% List.filter is eager. But we need a lazy Filter:
  fun lazy {LFilter Xs P}
     case Xs of X|Xr andthen {P X} then X|{LFilter Xr P}
     [] _|Xr then {LFilter Xr P}
     [] nil then nil
     end
  end

  HappyNumbers = {LFilter {Nat 1} IsHappy}
in
  {System.show {List.take HappyNumbers 8}}
end


Program HappyNumbers (output);

uses
  Math;

function find(n: integer; cache: array of integer): boolean;
  var
    i: integer;
  begin
    find := false;
    for i := low(cache) to high(cache) do
      if cache[i] = n then
        find := true;
  end;

function is_happy(n: integer): boolean;
  var
    cache: array of integer;
    sum: integer;
  begin
    setlength(cache, 1);
    repeat
      sum := 0;
      while n > 0 do
      begin
        sum := sum + (n mod 10)**2;
        n := n div 10;
      end;
      if sum = 1 then
      begin
        is_happy := true;
        break;
      end;
      if find(sum, cache) then
      begin
        is_happy := false;
        break;
      end;
      n := sum;
      cache[high(cache)]:= sum;
      setlength(cache, length(cache)+1);
    until false;
  end;

var
  n, count: integer;

begin
  n := 1;
  count := 0;
  while count < 8 do
  begin
    if is_happy(n) then
    begin
      inc(count);
      write(n, ' ');
    end;
    inc(n);
  end;
  writeln;
end.


use List::Util qw(sum);

sub ishappy {
  my $s = shift;
  while ($s > 6 && $s != 89) {
    $s = sum(map { $_*$_ } split(//,$s));
  }
  $s == 1;
}

my $n = 0;
print join(" ", map { 1 until ishappy(++$n); $n; } 1..8), "\n";


function is_happy(integer n)
    sequence seen = {}
    while n>1 do
        seen &= n
        integer k = 0
        while n>0 do
            k += power(remainder(n,10),2)
            n = floor(n/10)
        end while
        n = k
        if find(n,seen) then
            return false
        end if
    end while
    return true
end function

integer n = 1
sequence s = {}
while length(s)<8 do
    if is_happy(n) then
        s &= n
    end if
    n += 1
end while
?s


function isHappy($n) {
    while (1) {
        $total = 0;
        while ($n > 0) {
            $total += pow(($n % 10), 2);
            $n /= 10;
        }
        if ($total == 1)
            return true;
        if (array_key_exists($total, $past))
            return false;
        $n = $total;
        $past[$total] = 0;
    }
}

$i = $cnt = 0;
while ($cnt < 8) {
    if (isHappy($i)) {
        echo "$i ";
        $cnt++;
    }
    $i++;
}


go =>
   println(happy_len(8)).

happy(N) =>
   S = [N],
   Happy = 1,
   while (Happy == 1, N > 1)
     N := sum([to_integer(I)**2 : I in N.to_string()]),
     if member(N,S) then
       Happy := 0
     else
        S := S ++ [N]
     end
   end,
   Happy == 1.

happy_len(Limit) = S =>
   S = [],
   N = 1,
   while (S.length < Limit)
      if happy(N) then
         S := S ++ [N]
      end,
      N := N + 1
   end.


(de happy? (N)
   (let Seen NIL
      (loop
         (T (= N 1) T)
         (T (member N Seen))
         (setq N
            (sum '((C) (** (format C) 2))
               (chop (push 'Seen N)) ) ) ) ) )

(let H 0
   (do 8
      (until (happy? (inc 'H)))
      (printsp H) ) )


C :max=8
  :n=0
  :i=0
*test
U :*happy
T (a=1):#n
C (a=1):i=i+1
C :n=n+1
J (i<max):*test
E :

*happy
C :a=n
  :x=n
U :*sumsq
C :b=s
*loop
C :x=a
U :*sumsq
C :a=s
C :x=b
U :*sumsq
C :x=s
U :*sumsq
C :b=s
J (a<>b):*loop
E :

*sumsq
C :s=0
*digit
C :y=x/10
  :z=x-y*10
  :s=s+z*#z
  :x=y
J (x):*digit
E :


test: proc options (main); /* 19 November 2011 */
   declare (i, j, n, m, nh initial (0) ) fixed binary (31);

main_loop:
   do j = 1 to 100;
      n = j;
      do i = 1 to 100;
         m = 0;
         /* Form the sum of squares of the digits. */
         do until (n = 0);
            m = m + mod(n, 10)**2;
            n = n/10;
         end;
         if m = 1 then
            do;
               put skip list (j || ' is a happy number');
               nh = nh + 1;
               if nh = 8 then return;
               iterate main_loop;
            end;
         n = m; /* Replace n with the new number formed from digits. */
      end;
   end;
end test;


100H:

/* FIND SUM OF SQUARE OF DIGITS OF NUMBER */
DIGIT$SQUARE: PROCEDURE (N) BYTE;
    DECLARE (N, T, D) BYTE;
    T = 0;
    DO WHILE N > 0;
        D = N MOD 10;
        T = T + D * D;
        N = N / 10;
    END;
    RETURN T;
END DIGIT$SQUARE;

/* CHECK IF NUMBER IS HAPPY */
HAPPY: PROCEDURE (N) BYTE;
    DECLARE (N, I) BYTE;
    DECLARE FLAG (256) BYTE;

    DO I=0 TO 255;
        FLAG(I) = 0;
    END;

    DO WHILE NOT FLAG(N);
        FLAG(N) = 1;
        N = DIGIT$SQUARE(N);
    END;

    RETURN N = 1;
END HAPPY;

/* CP/M BDOS CALL */
BDOS: PROCEDURE (FN, ARG);
    DECLARE FN BYTE, ARG ADDRESS;
    GO TO 5;
END BDOS;

/* PRINT STRING */
PRINT: PROCEDURE (STR);
    DECLARE STR ADDRESS;
    CALL BDOS(9, STR);
END PRINT;

/* PRINT NUMBER */
PRINT$NUMBER: PROCEDURE (N);
    DECLARE S (6) BYTE INITIAL ('...',13,10,'$');
    DECLARE P ADDRESS;
    DECLARE (N, C BASED P) BYTE;
    P = .S(3);
DIGIT:
    P = P - 1;
    C = (N MOD 10) + '0';
    N = N / 10;
    IF N > 0 THEN GO TO DIGIT;
    CALL PRINT(P);
END PRINT$NUMBER;

/* FIND FIRST 8 HAPPY NUMBERS */
DECLARE SEEN BYTE INITIAL (0);
DECLARE N BYTE INITIAL (1);

DO WHILE SEEN < 8;
    IF HAPPY(N) THEN DO;
        CALL PRINT$NUMBER(N);
        SEEN = SEEN + 1;
    END;
    N = N + 1;
END;

CALL BDOS(0,0);
EOF


sqr = (n): n * n.

isHappy = (n) :
   loop :
      if (n == 1): return true.
      if (n == 4): return false.
      sum = 0
      n = n string
      n length times (i): sum = sum + sqr(n(i) number integer).
      n = sum
   .
.

firstEight = ()
i = 0
while (firstEight length < 8) :
   i++
   if (isHappy(i)): firstEight append(i).
.
firstEight string print


function happy([int] $n) {
    $a[email protected]()
    for($i=2;$a.count -lt $n;$i++) {
        $sum=$i
        $hist[email protected]{}
        while( $hist[$sum] -eq $null ) {
            if($sum -eq 1) {
                $a+=$i
            }
            $hist[$sum]=$sum
            $sum2=0
            foreach($j in $sum.ToString().ToCharArray()) {
                $k=([int]$j)-0x30
                $sum2+=$k*$k
            }
            $sum=$sum2
        }
    }
    $a -join ','
}


happy_numbers(L, Nb) :-
    % creation of the list
    length(L, Nb),
    % Process of this list
    get_happy_number(L, 1).

% the game is over
get_happy_number([], _).

% querying the newt happy_number
get_happy_number([H | T], N) :-
     N1 is N+1,
    (is_happy_number(N) ->
        H = N,
        get_happy_number(T, N1);
        get_happy_number([H | T], N1)).

% we must memorized the numbers reached
is_happy_number(N) :-
    is_happy_number(N, [N]).

% a number is happy when we get 1
is_happy_number(N, _L) :-
    get_next_number(N, 1), !.

% or when this number is not already reached !
is_happy_number(N, L) :-
    get_next_number(N, NN),
    \+member(NN, L),
    is_happy_number(NN, [NN | L]).

% Process of the next number from N
get_next_number(N, NewN) :-
    get_list_digits(N, LD),
    maplist(square, LD, L),
    sumlist(L, NewN).

get_list_digits(N, LD) :-
	number_chars(N, LCD),
	maplist(number_chars_, LD, LCD).

number_chars_(D, CD) :-
	number_chars(D, [CD]).

square(N, SN) :-
	SN is N * N.


#ToFind=8
#MaxTests=100
#True = 1: #False = 0
Declare is_happy(n)

If OpenConsole()
  Define i=1,Happy
  Repeat
    If is_happy(i)
      Happy+1
      PrintN("#"+Str(Happy)+RSet(Str(i),3))
    EndIf
    i+1
  Until Happy>=#ToFind
  ;
  Print(#CRLF$+#CRLF$+"Press ENTER to exit"): Input()
  CloseConsole()
EndIf

Procedure is_happy(n)
  Protected i,j=n,dig,sum
  Repeat
    sum=0
    While j
      dig=j%10
      j/10
      sum+dig*dig
    Wend
    If sum=1: ProcedureReturn #True: EndIf
    j=sum
    i+1
  Until i>#MaxTests
  ProcedureReturn #False
EndProcedure


>>> def happy(n):
    past = set()
    while n != 1:
        n = sum(int(i)**2 for i in str(n))
        if n in past:
            return False
        past.add(n)
    return True

>>> [x for x in xrange(500) if happy(x)][:8]
[1, 7, 10, 13, 19, 23, 28, 31]


  [ 0 swap
    [ 10 /mod 2 **
      rot + swap
      dup 0 = until ]
    drop ]                  is digitsquare ( n --> n )

  [ [ digitsquare
      dup  1 != while
      dup 42 != while
      again ]
    1 = ]                   is happy       ( n --> b )

  [ [] 1
    [ dip
      [ 2dup size > ]
      swap while
      dup happy if
        [ tuck join swap ]
      1+ again ]
    drop nip ]             is happies      ( n --> [ )

  8 happies echo


is.happy <- function(n)
{
   stopifnot(is.numeric(n) && length(n)==1)
   getdigits <- function(n)
   {
      as.integer(unlist(strsplit(as.character(n), "")))
   }
   digits <- getdigits(n)
   previous <- c()
   repeat
   {
      sumsq <- sum(digits^2, na.rm=TRUE)
      if(sumsq==1L)
      {
         happy <- TRUE
         break
      } else if(sumsq %in% previous)
      {
         happy <- FALSE
         attr(happy, "cycle") <- previous
         break
      } else
      {
         previous <- c(previous, sumsq)
         digits <- getdigits(sumsq)
      }
   }
   happy
}


#lang racket
(define (sum-of-squared-digits number (result 0))
  (if (zero? number)
      result
      (sum-of-squared-digits (quotient number 10)
                             (+ result (expt (remainder number 10) 2)))))

(define (happy-number? number (seen null))
  (define next (sum-of-squared-digits number))
  (cond ((= 1 next)
         #t)
        ((memq next seen)
         #f)
        (else
         (happy-number? next (cons number seen)))))

(define (get-happys max)
  (for/list ((x (in-range max))
             #:when (happy-number? x))
    x))

(display (take (get-happys 100) 8)) ;displays (1 7 10 13 19 23 28 31)


sub happy (Int $n is copy --> Bool) {
  loop {
      state %seen;
      $n = [+] $n.comb.map: { $_ ** 2 }
      return True  if $n == 1;
      return False if %seen{$n}++;
  }
}

say join ' ', grep(&happy, 1 .. *)[^8];


function happy(x)
set y = x
set lasty = 0
set found = " "
while y !=  1 and not (found regex "\s".y."\s")
set found = found . y . " "
set m = 0
while y  > 0
set digit = y mod 10
set m = m + digit * digit
set y = (y - digit) / 10
end while
set y = format(m,"%1d")
end while
set found = found . y . " "
if y = 1
set result = 1
else
set result = 0
end if
end function

set c = 0
set i = 1
while c < 8 and i < 100
if happy(i)
echo i
set c = c + 1
end if
set i = i + 1
end while


/*REXX program  computes  and  displays  a  specified  amount  of   happy   numbers.    */
parse arg limit .                                /*obtain optional argument from the CL.*/
if limit=='' | limit==","  then limit=8          /*Not specified?  Then use the default.*/
haps=0                                           /*count of the happy numbers  (so far).*/

  do n=1  while haps<limit;    @.=0;  q=n        /*search the integers starting at unity*/
         do  until q==1                          /*determine if   Q   is a happy number.*/
         s=0                                     /*prepare to add squares of digits.    */
                 do j=1  for length(q)           /*sum the squares of the decimal digits*/
                 s=s + substr(q, j, 1) **2       /*add the square  of  a  decimal digit.*/
                 end   /*j*/

         if @.s  then iterate n                  /*if already summed,   Q   is unhappy. */
         @.s=1;  q=s                             /*mark the sum as found;   try  Q  sum.*/
         end   /*until*/
  say n                                          /*display the number    (N  is happy). */
  haps=haps+1                                    /*bump the  count  of  happy numbers.  */
  end          /*n*/
                                                 /*stick a fork in it,  we're all done. */


n = 1
found = 0

While found < 8
    If IsHappy(n)
          found += 1
          see string(found) + " : " + string(n) + nl
    ok
    n += 1
End

Func IsHappy n
    cache = []
    While n != 1
        Add(cache,n)
        t = 0
        strn = string(n)
        for e in strn
            t += pow(number(e),2)
        next
        n = t
        If find(cache,n) Return False ok
    End
    Return True


require 'set' # Set: Fast array lookup / Simple existence hash

@seen_numbers = Set.new
@happy_numbers = Set.new

def happy?(n)
  return true if n == 1 # Base case
  return @happy_numbers.include?(n) if @seen_numbers.include?(n) # Use performance cache, and stop unhappy cycles

  @seen_numbers << n
  digit_squared_sum = n.to_s.each_char.inject(0) { |sum, c| sum + c.to_i**2 } # In Rails: n.to_s.each_char.sum { c.to_i**2 }

  if happy?(digit_squared_sum)
    @happy_numbers << n
    true # Return true
  else
    false # Return false
  end
end


for i = 1 to 100
 if happy(i) = 1 then
  cnt = cnt + 1
  PRINT cnt;". ";i;" is a happy number "
  if cnt = 8 then end
 end if
next i

FUNCTION happy(num)
while count < 50 and happy <> 1
  num$	= str$(num)
  count	= count + 1
  happy	= 0
  for i = 1 to len(num$)
    happy = happy + val(mid$(num$,i,1)) ^ 2
  next i
  num = happy
wend
end function


#![feature(core)]

fn sumsqd(mut n: i32) -> i32 {
    let mut sq = 0;
    while n > 0 {
        let d = n % 10;
        sq += d*d;
        n /= 10
    }
    sq
}

use std::num::Int;
fn cycle<T: Int>(a: T, f: fn(T) -> T) -> T {
    let mut t = a;
    let mut h = f(a);

    while t != h {
        t = f(t);
        h = f(f(h))
    }
    t
}

fn ishappy(n: i32) -> bool {
    cycle(n, sumsqd) == 1
}

fn main() {
    let happy = std::iter::count(1, 1)
                    .filter(|&n| ishappy(n))
                    .take(8)
                    .collect::<Vec<i32>>();

    println!("{:?}", happy)
}


variable happy_count := 0;
outer:
iterate(x; [1...+oo])
  {
    variable seen := <<(* --> false)>>;
    variable now := x;
    while (true)
      {
        if (seen[now])
          {
            if (now == 1)
              {
                ++happy_count;
                print(x, " is happy.\n");
                if (happy_count == 8)
                    break from outer;;
              };
            break;
          };
        seen[now] := true;
        variable new := 0;
        while (now != 0)
          {
            new += (now % 10) * (now % 10);
            now /::= 10;
          };
        now := new;
      };
  };


scala> def isHappy(n: Int) = {
     |   new Iterator[Int] {
     |   val seen = scala.collection.mutable.Set[Int]()
     |   var curr = n
     |   def next = {
     |     val res = curr
     |     curr = res.toString.map(_.asDigit).map(n => n * n).sum
     |     seen += res
     |     res
     |   }
     |   def hasNext = !seen.contains(curr)
     | }.toList.last == 1
     | }
isHappy: (n: Int)Boolean

scala> Iterator from 1 filter isHappy take 8 foreach println
1
7
10
13
19
23
28
31


(define (number->list num)
  (do ((num num (quotient num 10))
       (lst '() (cons (remainder num 10) lst)))
    ((zero? num) lst)))

(define (happy? num)
  (let loop ((num num) (seen '()))
    (cond ((= num 1) #t)
          ((memv num seen) #f)
          (else (loop (apply + (map (lambda (x) (* x x)) (number->list num)))
                      (cons num seen))))))

(display "happy numbers:")
(let loop ((n 1) (more 8))
  (cond ((= more 0) (newline))
        ((happy? n) (display " ") (display n) (loop (+ n 1) (- more 1)))
        (else (loop (+ n 1) more))))


$ include "seed7_05.s7i";

const type: cacheType is hash [integer] boolean;
var cacheType: cache is cacheType.value;

const func boolean: happy (in var integer: number) is func
  result
    var boolean: isHappy is FALSE;
  local
    var bitset: cycle is bitset.value;
    var integer: newnumber is 0;
    var integer: cycleNum is 0;
  begin
    while number > 1 and number not in cycle do
      if number in cache then
        number := ord(cache[number]);
      else
        incl(cycle, number);
        newnumber := 0;
        while number > 0 do
          newnumber +:= (number rem 10) ** 2;
          number := number div 10;
        end while;
        number := newnumber;
      end if;
    end while;
    isHappy := number = 1;
    for cycleNum range cycle do
      cache @:= [cycleNum] isHappy;
    end for;
  end func;

const proc: main is func
  local
    var integer: number is 0;
  begin
    for number range 1 to 50 do
      if happy(number) then
        writeln(number);
      end if;
    end for;
  end func;


import <Utilities/Math.sl>;
import <Utilities/Conversion.sl>;

main(argv(2)) := findHappys(stringToInt(head(argv)));

findHappys(count) := findHappysHelper(count, 1, []);

findHappysHelper(count, n, happys(1)) :=
        happys when size(happys) = count
    else
        findHappysHelper(count, n + 1, happys ++ [n]) when isHappy(n)
    else
        findHappysHelper(count, n + 1, happys);

isHappy(n) := isHappyHelper(n, []);

isHappyHelper(n, cache(1)) :=
    let
        digits[i] := (n / integerPower(10, i - 1)) mod 10
                    foreach i within 1 ... ceiling(log(10, n + 1));
        newN := sum(integerPower(digits, 2));
    in
        false when some(n = cache)
    else
        true when n = 1
    else
        isHappyHelper(newN, cache ++ [n]);


proc is_happy(n);
  s := [n];
  while n > 1 loop
    if (n := +/[val(i)**2: i in str(n)]) in s then
       return false;
    end if;
    s with:= n;
  end while;
  return true;
end proc;


func happy(n) is cached {
    static seen = Hash()

    return true  if n.is_one
    return false if seen.exists(n)

    seen{n} = 1
    happy(n.digits.sum { _*_ })
}

say happy.first(8)


Object subclass: HappyNumber [
  |cache negativeCache|
  HappyNumber class >> new [ |me|
    me := super new.
    ^ me init
  ]
  init [ cache := Set new. negativeCache := Set new. ]

  hasSad: aNum [
    ^ (negativeCache includes: (self recycle: aNum))
  ]
  hasHappy: aNum [
    ^ (cache includes: (self recycle: aNum))
  ]
  addHappy: aNum [
    cache add: (self recycle: aNum)
  ]
  addSad: aNum [
    negativeCache add: (self recycle: aNum)
  ]

  recycle: aNum [ |r n| r := Bag new.
    n := aNum.
    [ n > 0 ]
    whileTrue: [ |d|
      d := n rem: 10.
      r add: d.
      n := n // 10.
    ].
    ^r
  ]

  isHappy: aNumber [ |cycle number newnumber|
    number := aNumber.
    cycle := Set new.
    [ (number ~= 1) & ( (cycle includes: number) not ) ]
    whileTrue: [
      (self hasHappy: number)
      ifTrue: [ ^true ]
      ifFalse: [
        (self hasSad: number) ifTrue: [ ^false ].
        cycle add: number.
        newnumber := 0.
        [ number > 0 ]
        whileTrue: [ |digit|
          digit := number rem: 10.
          newnumber := newnumber + (digit * digit).
 	  number := (number - digit) // 10.
        ].
        number := newnumber.
      ]
    ].
    (number = 1)
    ifTrue: [
      cycle do: [ :e | self addHappy: e ].
      ^true
    ]
    ifFalse: [
      cycle do: [ :e | self addSad: e ].
      ^false
    ]
  ]
].


func isHappyNumber(var n:Int) -> Bool {
    var cycle = [Int]()

    while n != 1 && !cycle.contains(n) {
        cycle.append(n)
        var m = 0
        while n > 0 {
            let d = n % 10
            m += d * d
            n = (n  - d) / 10
        }
        n = m
    }
    return n == 1
}

var found = 0
var count = 0
while found != 8 {
    if isHappyNumber(count) {
        print(count)
        found++
    }
    count++
}


proc is_happy n {
    set seen [list]
    while {$n > 1 && [lsearch -exact $seen $n] == -1} {
        lappend seen $n
        set n [sum_of_squares [split $n ""]]
    }
    return [expr {$n == 1}]
}

set happy [list]
set n -1
while {[llength $happy] < 8} {
    if {[is_happy $n]} {lappend happy $n}
    incr n
}
puts "the first 8 happy numbers are: [list $happy]"


$$ MODE TUSCRIPT
SECTION check
  IF (n!=1) THEN
   n = STRINGS (n,":>/:")
    LOOP/CLEAR nr=n
     square=nr*nr
     n=APPEND (n,square)
    ENDLOOP
   n=SUM(n)
   r_table=QUOTES (n)
   BUILD R_TABLE/word/EXACT chk=r_table
   IF (seq.ma.chk) THEN
    status="next"
   ELSE
    seq=APPEND (seq,n)
   ENDIF
   RELEASE r_table chk
  ELSE
    PRINT checkednr," is a happy number"
    happynrs=APPEND (happynrs,checkednr)
    status="next"
  ENDIF
ENDSECTION

happynrs=""

LOOP n=1,100
sz_happynrs=SIZE(happynrs)
IF (sz_happynrs==8) EXIT
checkednr=VALUE(n)
status=seq=""
 LOOP
  IF (status=="next") EXIT
  DO check
 ENDLOOP
ENDLOOP


' ************************
' MAIN
' ************************

PROC _PRINT_HAPPY(20)
END

' ************************
' END MAIN
' ************************

' ************************
' SUBS & FUNCTIONS
' ************************

' --------------------
_is_happy PARAM(1)
' --------------------
LOCAL (5)
  [email protected] = 100
  [email protected] = [email protected]
  [email protected] = 0

  DO WHILE [email protected] < [email protected]
    [email protected] = 0

    DO WHILE [email protected]
      [email protected] = [email protected] % 10
      [email protected] = [email protected] / 10
      [email protected] = [email protected] + ([email protected] * [email protected])
    LOOP

  UNTIL [email protected] = 1
    [email protected] = [email protected]
    [email protected] = [email protected] + 1
  LOOP

RETURN([email protected] < [email protected])

' --------------------
_PRINT_HAPPY PARAM(1)
' --------------------
LOCAL (2)
  [email protected] = 1
  [email protected] = 0

  DO

    IF FUNC (_is_happy([email protected])) THEN
       [email protected] = [email protected] + 1
       PRINT [email protected]
    ENDIF

    [email protected] = [email protected] + 1
    UNTIL [email protected] + 1 > [email protected]
  LOOP

RETURN

' ************************
' END SUBS & FUNCTIONS
' ************************


#!/bin/bash
function sum_of_square_digits
{
  local -i n="$1" sum=0
  while (( n )); do
    local -i d=n%10
    let sum+=d*d
    let n=n/10
  done
  echo "$sum"
}

function is_happy?
{
   local -i n="$1"
   local seen=()
   while (( n != 1 )); do
     if [ -n "${seen[$n]}" ]; then
        return 1
     fi
     seen[n]=1
     let n="$(sum_of_square_digits "$n")"
   done
   return 0
}

function first_n_happy
{
  local -i count="$1"
  local -i n
  for (( n=0; count; n+=1 )); do
  if is_happy? "$n"; then
    echo "$n"
    let count-=1
  fi
  done
  return 0
}

first_n_happy 8


#import std
#import nat

happy = ==1+ ^== sum:-0+ product*iip+ %np*hiNCNCS+ %nP

first "p" = ~&i&& iota; ~&lrtPX/&; [email protected]>lrx ^|\~& ^/[email protected] ^|T\~& "p"&& ~&iNC

#cast %nL

main = (first happy) 8


using Gee;

/* function to sum the square of the digits */
int sum(int input){
	// convert input int to string
	string input_str = input.to_string();
	int total = 0;
	// read through each character in string, square them and add to total
	for (int x = 0; x < input_str.length; x++){
		// char.digit_value converts char to the decimal value the char it represents holds
		int digit = input_str[x].digit_value();
		total += (digit * digit);
	}

	return total;
} // end sum

/* function to decide if a number is a happy number */
bool is_happy(int total){
	var past = new HashSet<int>();
	while(true){
		total = sum(total);
		if (total == 1){
			return true;}

		if (total in past){
			return false;}

		past.add(total);
	} // end while loop
} // end happy

public static void main(){
	var happynums = new ArrayList<int>();
	int x = 1;

	while (happynums.size < 8){
		if (is_happy(x) == true)
			happynums.add(x);
		x++;
	}

	foreach(int num in happynums)
		stdout.printf("%d ", num);
	stdout.printf("\n");
} // end main


Option Explicit

Sub Test_Happy()
Dim i&, Cpt&

    For i = 1 To 100
        If Is_Happy_Number(i) Then
            Debug.Print "Is Happy : " & i
            Cpt = Cpt + 1
            If Cpt = 8 Then Exit For
        End If
    Next
End Sub

Public Function Is_Happy_Number(ByVal N As Long) As Boolean
Dim i&, Number$, Cpt&
    Is_Happy_Number = False 'default value
    Do
        Cpt = Cpt + 1       'Count Loops
        Number = CStr(N)    'conversion Long To String to be able to use Len() function
        N = 0
        For i = 1 To Len(Number)
            N = N + CInt(Mid(Number, i, 1)) ^ 2
        Next i
        'If Not N = 1 after 50 Loop ==> Number Is Not Happy
        If Cpt = 50 Then Exit Function
    Loop Until N = 1
    Is_Happy_Number = True
End Function


count = 0
firsteigth=""
For i = 1 To 100
	If IsHappy(CInt(i)) Then
		firsteight = firsteight & i & ","
		count = count + 1
	End If
	If count = 8 Then
		Exit For
	End If
Next
WScript.Echo firsteight

Function IsHappy(n)
	IsHappy = False
	m = 0
	Do Until m = 60
		sum = 0
		For j = 1 To Len(n)
			sum = sum + (Mid(n,j,1))^2
		Next
		If sum = 1 Then
			IsHappy = True
			Exit Do
		Else
			n = sum
			m = m + 1
		End If
	Loop
End Function


Module HappyNumbers
    Sub Main()
        Dim n As Integer = 1
        Dim found As Integer = 0

        Do Until found = 8
            If IsHappy(n) Then
                found += 1
                Console.WriteLine("{0}: {1}", found, n)
            End If
            n += 1
        Loop

        Console.ReadLine()
    End Sub

    Private Function IsHappy(ByVal n As Integer)
        Dim cache As New List(Of Long)()

        Do Until n = 1
            cache.Add(n)
            n = Aggregate c In n.ToString() _
                Into Total = Sum(Int32.Parse(c) ^ 2)
            If cache.Contains(n) Then Return False
        Loop

        Return True
    End Function
End Module


fn happy(h int) bool {
    mut m := map[int]bool{}
    mut n := h
    for n > 1 {
        m[n] = true
        mut x := 0
        for x, n = n, 0; x > 0; x /= 10 {
            d := x % 10
            n += d * d
        }
        if m[n] {
            return false
        }
    }
    return true
}

fn main() {
    for found, n := 0, 1; found < 8; n++ {
        if happy(n) {
            print("$n ")
            found++
        }
    }
    println('')
}


var happy = Fn.new { |n|
    var m = {}
    while (n > 1) {
        m[n] = true
        var x = n
        n = 0
        while (x > 0) {
            var d = x % 10
            n = n + d*d
            x = (x/10).floor
        }
        if (m[n] == true) return false // m[n] will be null if 'n' is not a key
    }
    return true
}

var found = 0
var n = 1
while (found < 8) {
    if (happy.call(n)) {
        System.write("%(n) ")
        found = found + 1
    }
    n = n + 1
}
System.print()


int List(810);          \list of numbers in a cycle
int Inx;                \index for List
include c:\cxpl\codes;

func HadNum(N);         \Return 'true' if number N is in the List
int N;
int I;
[for I:= 0 to Inx-1 do
        if N = List(I) then return true;
return false;
]; \HadNum

func SqDigits(N);       \Return the sum of the squares of the digits of N
int N;
int S, D;
[S:= 0;
while N do
        [N:= N/10;
        D:= rem(0);
        S:= S + D*D;
        ];
return S;
]; \SqDigits

int N0, N, C;
[N0:= 0;                \starting number
C:= 0;                  \initialize happy (starting) number counter
repeat  N:= N0;
        Inx:= 0;        \reset List index
        loop    [N:= SqDigits(N);
                if N = 1 then                   \happy number
                        [IntOut(0, N0);  CrLf(0);
                        C:= C+1;
                        quit;
                        ];
                if HadNum(N) then quit;         \if unhappy number then quit
                List(Inx):= N;                  \if neither, add it to the List
                Inx:= Inx+1;                    \ and continue the cycle
                ];
        N0:= N0+1;                              \next starting number
until   C=8;            \done when 8 happy numbers have been found
]


const std = @import("std");
const stdout = std.io.getStdOut().outStream();

pub fn main() !void {
    try stdout.print("The first 8 happy numbers are: ", .{});
    var n: u32 = 1;
    var c: u4 = 0;
    while (c < 8) {
        if (isHappy(n)) {
            c += 1;
            try stdout.print("{} ", .{n});
        }
        n += 1;
    }
    try stdout.print("\n", .{});
}

fn isHappy(n: u32) bool {
    var t = n;
    var h = sumsq(n);
    while (t != h) {
        t = sumsq(t);
        h = sumsq(sumsq(h));
    }
    return t == 1;
}

fn sumsq(n0: u32) u32 {
    var s: u32 = 0;
    var n = n0;
    while (n > 0) : (n /= 10) {
        const m = n % 10;
        s += m * m;
    }
    return s;
}


fcn happyNumbers{  // continously spew happy numbers
   foreach N in ([1..]){
       n:=N; while(1){
	 n=n.split().reduce(fcn(p,n){ p + n*n },0);
	 if(n==1) { vm.yield(N); break; }
	 if(n==4) break;  // unhappy cycle
      }
   }
}


10 FOR i=1 TO 100
20 GO SUB 1000
30 IF isHappy=1 THEN PRINT i;" is a happy number"
40 NEXT i
50 STOP
1000 REM Is Happy?
1010 LET isHappy=0: LET count=0: LET num=i
1020 IF count=50 OR isHappy=1 THEN RETURN
1030 LET n$=STR$ (num)
1040 LET count=count+1
1050 LET isHappy=0
1060 FOR j=1 TO LEN n$
1070 LET isHappy=isHappy+VAL n$(j)^2
1080 NEXT j
1090 LET num=isHappy
1100 GO TO 1020


with Ada.Strings.Fixed;
with Gtk.Main;
with Gtk.Handlers;
with Gtk.Button;
with Gtk.Window;
with Gtk.GEntry;
with Gtk.Editable;
with Gtk.Box;
with Gtk.Widget;
with Glib.Values;

procedure Disabling is
   type My_Natural is range 0 .. 10;

   The_Value : My_Natural := 0;

   Main_Window      : Gtk.Window.Gtk_Window;
   Content          : Gtk.Box.Gtk_Vbox;
   Increment_Button : Gtk.Button.Gtk_Button;
   Decrement_Button : Gtk.Button.Gtk_Button;
   Entry_Field      : Gtk.GEntry.Gtk_Entry;

   package Entry_Callbacks is new Gtk.Handlers.Callback
     (Gtk.GEntry.Gtk_Entry_Record);

   package Button_Callbacks is new Gtk.Handlers.Callback
     (Gtk.Button.Gtk_Button_Record);

   package Window_Callbacks is new Gtk.Handlers.Return_Callback
     (Gtk.Window.Gtk_Window_Record, Boolean);

   --  update displayed text
   procedure Update_Entry is
   begin
      Gtk.GEntry.Set_Text
        (The_Entry => Entry_Field,
         Text      =>
           Ada.Strings.Fixed.Trim
             (Source => My_Natural'Image (The_Value),
              Side   => Ada.Strings.Both));
   end Update_Entry;

   procedure Check_Value is
   begin
      Gtk.Widget.Set_Sensitive
        (Gtk.Widget.Gtk_Widget (Decrement_Button),
         The_Value > 0);
      Gtk.Widget.Set_Sensitive
        (Gtk.Widget.Gtk_Widget (Increment_Button),
         The_Value < 10);
      Gtk.Widget.Set_Sensitive
        (Gtk.Widget.Gtk_Widget (Entry_Field),
         The_Value = 0);
   end Check_Value;

   procedure On_Changed_Text
     (Object : access Gtk.GEntry.Gtk_Entry_Record'Class;
      Params : Glib.Values.GValues)
   is
      pragma Unreferenced (Params, Object);
   begin
      The_Value := My_Natural'Value (Gtk.GEntry.Get_Text (Entry_Field));
      Check_Value;
      Update_Entry;
   exception
      when Constraint_Error =>
         The_Value := 0;
   end On_Changed_Text;

   --  make sure that only numbers are entered
   procedure On_Insert_Text
     (Object : access Gtk.GEntry.Gtk_Entry_Record'Class;
      Params : Glib.Values.GValues)
   is
      Length : constant Glib.Gint :=
        Glib.Values.Get_Int (Glib.Values.Nth (Params, 2));
      Text   : constant String    :=
        Glib.Values.Get_String (Glib.Values.Nth (Params, 1), Length);
   begin
      declare
         Number : My_Natural;
         pragma Unreferenced (Number);
      begin
         Number := My_Natural'Value (Text);
      exception
         when Constraint_Error =>
            --  refuse values that are not parsable
            Gtk.Handlers.Emit_Stop_By_Name
              (Object => Object,
               Name   => Gtk.Editable.Signal_Insert_Text);
      end;
   end On_Insert_Text;

   --  Callback for click event
   procedure On_Increment_Click
     (Object : access Gtk.Button.Gtk_Button_Record'Class)
   is
      pragma Unreferenced (Object);
   begin
      The_Value := The_Value + 1;
      Check_Value;
      Update_Entry;
   end On_Increment_Click;

   --  Callback for click event
   procedure On_Decrement_Click
     (Object : access Gtk.Button.Gtk_Button_Record'Class)
   is
      pragma Unreferenced (Object);
   begin
      The_Value := The_Value - 1;
      Check_Value;
      Update_Entry;
   end On_Decrement_Click;

   --  Callback for delete event
   function On_Main_Window_Delete
     (Object : access Gtk.Window.Gtk_Window_Record'Class)
      return   Boolean
   is
      pragma Unreferenced (Object);
   begin
      Gtk.Main.Main_Quit;
      return True;
   end On_Main_Window_Delete;

begin

   Gtk.Main.Init;

   Gtk.GEntry.Gtk_New (Widget => Entry_Field);
   Entry_Callbacks.Connect
     (Widget => Entry_Field,
      Name   => Gtk.Editable.Signal_Insert_Text,
      Cb     => On_Insert_Text'Access);
   Entry_Callbacks.Connect
     (Widget => Entry_Field,
      Name   => Gtk.Editable.Signal_Changed,
      Cb     => On_Changed_Text'Access);

   Gtk.Button.Gtk_New (Button => Increment_Button, Label => "Increment");
   Gtk.Button.Gtk_New (Button => Decrement_Button, Label => "Decrement");

   Button_Callbacks.Connect
     (Widget => Increment_Button,
      Name   => Gtk.Button.Signal_Clicked,
      Marsh  => Button_Callbacks.To_Marshaller (On_Increment_Click'Access));
   Button_Callbacks.Connect
     (Widget => Decrement_Button,
      Name   => Gtk.Button.Signal_Clicked,
      Marsh  => Button_Callbacks.To_Marshaller (On_Decrement_Click'Access));

   Gtk.Box.Gtk_New_Vbox (Box => Content);
   Gtk.Box.Add (Container => Content, Widget => Entry_Field);
   Gtk.Box.Add (Container => Content, Widget => Increment_Button);
   Gtk.Box.Add (Container => Content, Widget => Decrement_Button);

   Gtk.Window.Gtk_New (Window => Main_Window);
   Gtk.Window.Add (Container => Main_Window, Widget => Content);

   Window_Callbacks.Connect
     (Widget => Main_Window,
      Name   => Gtk.Widget.Signal_Delete_Event,
      Cb     => On_Main_Window_Delete'Access);
   Gtk.Window.Show_All (Widget => Main_Window);
   Update_Entry;

   Gtk.Main.Main;
end Disabling;


GUI, Add, Edit, w150 number vValue gEnableDisable, 0 ; Number specifies a numbers-only edit field. g<Subroutine> specifies a subroutine to run when the value of control changes.
GUI, Add, button,, Increment
GUI, Add, button, xp+70 yp, Decrement ; xp+70 and yp are merely positioning options
GUI, Show, w200 y200, Title	      ; Shows the GUI. Add your own title if you wish
;No timer is needed
return 				      ; ----------End Auto-Execute Section----------

ButtonIncrement:
    GUI, Submit, NoHide         ; "Set the contents of each variable to the contents of their corresponding controls without hiding the GUI"
    If ( value < 10 )           ; Just in case EnableDisable didn't disable the button it in time.
        Value++                 ; Increment Value
    GUIControl,, Value, %value% ; "Set the text of the control which alters the variable 'value' to the contents of 'value'"
return

ButtonDecrement:
    GUI, Submit, Nohide
    If value > 0
        Value--
    GuiControl,, Value, %value%
return

EnableDisable:
    GUI, Submit, Nohide
    If ( value < 10 )
        GuiControl, enable, Increment
    Else
        GuiControl, disable, Increment

    If ( value > 0)
        GuiControl, enable, Decrement
    Else
        GuiControl, disable, Decrement

    If ( value = 0 )
        GuiControl, enable, Edit1
    Else
        GuiControl, disable, Edit1
return

GuiClose:
    ExitApp
; Ensures the script ends when the GUI is closed.


OPTION GUI TRUE
PRAGMA GUI gtk3

gui = GUIDEFINE(" \
    { type=WINDOW name=window callback=delete-event title=\"Rosetta Code\" width-request=200 } \
    { type=BOX name=box parent=window orientation=GTK_ORIENTATION_VERTICAL } \
    { type=SPIN_BUTTON name=spin parent=box numeric=TRUE } \
    { type=BUTTON_BOX name=bbox parent=box } \
    { type=BUTTON name=increment parent=bbox callback=clicked label=\"Increment\" } \
    { type=BUTTON name=decrement parent=bbox callback=clicked label=\"Decrement\" } ")

CALL GUISET(gui, "spin", "adjustment", gtk_adjustment_new(0, 0, 10, 1, 1, 0))
CALL GUISET(gui, "decrement", "sensitive", FALSE)

DECLARE input TYPE FLOATING

WHILE TRUE

    CALL GUIGET(gui, "spin", "value", &input)
    SELECT GUIEVENT$(gui)
        CASE "increment"
            INCR input
        CASE "decrement"
            DECR input
        CASE "window"
            BREAK
    ENDSELECT
    CALL GUISET(gui, "spin", "value", input)

    CALL GUISET(gui, "decrement", "sensitive", IIF(input <= 0, FALSE, TRUE))
    CALL GUISET(gui, "increment", "sensitive", IIF(input > 9, FALSE, TRUE))
    CALL GUISET(gui, "spin", "sensitive", IIF(input = 0, TRUE, FALSE))

WEND


      INSTALL @lib$+"WINLIB2"
      INSTALL @lib$+"WINLIB5"
      ES_NUMBER = 8192

      form% = FN_newdialog("Rosetta Code", 100, 100, 100, 52, 8, 1000)
      idInc% = FN_setproc(PROCinc)
      idDec% = FN_setproc(PROCdec)

      PROC_static(form%, "Value:", 100, 10, 10, 24, 14, 0)
      PROC_editbox(form%, "0", 101, 40, 8, 52, 14, ES_NUMBER)
      PROC_pushbutton(form%, "Increment", idInc%, 7, 30, 40, 16, 0)
      PROC_pushbutton(form%, "Decrement", idDec%, 52, 30, 40, 16, 0)
      PROC_showdialog(form%)

      REPEAT
        WAIT 1
        SYS "GetDlgItemInt", !form%, 101, 0, 1 TO number%
        SYS "GetDlgItem", !form%, 101 TO hedit%
        SYS "EnableWindow", hedit%, number% = 0
        SYS "GetDlgItem", !form%, idInc% TO hinc%
        SYS "EnableWindow", hinc%, number% < 10
        SYS "GetDlgItem", !form%, idDec% TO hdec%
        SYS "EnableWindow", hdec%, number% > 0
      UNTIL !form% = 0
      QUIT

      DEF PROCinc
      LOCAL number%
      SYS "GetDlgItemInt", !form%, 101, 0, 1 TO number%
      SYS "SetDlgItemInt", !form%, 101, number% + 1, 1
      ENDPROC

      DEF PROCdec
      LOCAL number%
      SYS "GetDlgItemInt", !form%, 101, 0, 1 TO number%
      SYS "SetDlgItemInt", !form%, 101, number% - 1, 1
      ENDPROC


using System;
using System.ComponentModel;
using System.Windows.Forms;

class RosettaInteractionForm : Form
{

    // Model used for DataBinding.
    // Notifies bound controls about Value changes.
    class NumberModel: INotifyPropertyChanged
    {
        // initialize event with empty delegate to avoid checks on null
        public event PropertyChangedEventHandler PropertyChanged = delegate {};

        int _value;
        public int Value
        {
            get { return _value; }
            set
            {
                _value = value;
                // Notify bound control about value change
                PropertyChanged(this, new PropertyChangedEventArgs("Value"));
            }
        }
    }

    NumberModel model = new NumberModel{ Value = 0};

    RosettaInteractionForm()
    {
        //MaskedTextBox is a TextBox variety with built-in input validation
        var tbNumber = new MaskedTextBox
                        {
                            Mask="0000",            // allow 4 decimal digits only
                            ResetOnSpace = false,   // don't enter spaces
                            Dock = DockStyle.Top    // place at the top of form
                        };
        // bound TextBox.Text to NumberModel.Value;
        tbNumber.DataBindings.Add("Text", model, "Value");
        var enabledIfZero = new Binding("Enabled", model, "Value");
        EnableControlWhen(tbNumber, value => value == 0);

        var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom};
        btIncrement.Click += delegate
                        {
                            model.Value++;
                        };
        EnableControlWhen(btIncrement, value => value < 10);
        var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom};
        btDecrement.Click += delegate
                        {
                            model.Value--;
                        };
        EnableControlWhen(btDecrement, value => value > 0);
        Controls.Add(tbNumber);
        Controls.Add(btIncrement);
        Controls.Add(btDecrement);
    }

    // common part of creating bindings for Enabled property
    void EnableControlWhen(Control ctrl, Func<int, bool> predicate)
    {
        // bind Control.Enabled to NumberModel.Value
        var enabledBinding = new Binding("Enabled", model, "Value");
        // Format event is called when model value should be converted to Control value.
        enabledBinding.Format += (sender, args) =>
            {
                // Enabled property is of bool type.
                if (args.DesiredType != typeof(bool)) return;
                // set resulting value by applying condition
                args.Value = predicate((int)args.Value);
            };
        // as a result, control will be enabled if predicate returns true
        ctrl.DataBindings.Add(enabledBinding);
    }

    static void Main()
    {
        Application.Run(new RosettaInteractionForm());
    }
}


type
  TForm1 = class(TForm)
    MaskEditValue: TMaskEdit; // Set Editmask on: "99;0; "
    SpeedButtonIncrement: TSpeedButton;
    SpeedButtonDecrement: TSpeedButton;
    procedure MaskEditValueChange(Sender: TObject);
    procedure SpeedButtonDecrementClick(Sender: TObject);
    procedure SpeedButtonIncrementClick(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

procedure TForm1.MaskEditValueChange(Sender: TObject);
begin
  TMaskEdit(Sender).Enabled := StrToIntDef(Trim(TMaskEdit(Sender).Text), 0) = 0;
  SpeedButtonIncrement.Enabled := StrToIntDef(Trim(TMaskEdit(Sender).Text), 0) < 10;
  SpeedButtonDecrement.Enabled := StrToIntDef(Trim(TMaskEdit(Sender).Text), 0) > 0;
end;

procedure TForm1.SpeedButtonDecrementClick(Sender: TObject);
begin
  MaskEditValue.Text := IntToStr(Pred(StrToIntDef(Trim(MaskEditValue.Text), 0)));
end;

procedure TForm1.SpeedButtonIncrementClick(Sender: TObject);
begin
  MaskEditValue.Text := IntToStr(Succ(StrToIntDef(Trim(MaskEditValue.Text), 0)));
end;


using fwt
using gfx

class Main
{
  public static Void main ()
  {
    Window
    {
      textField := Text
      {
        text = "0"
      }
      incButton := Button
      {
        text = "increment"
        onAction.add |Event e|
        {
          if (textField.text != "")
          {
            try
            {
              Int value := textField.text.toInt
              if (value < 10) value += 1
              textField.text = value.toStr
            }
            catch {}
          }
        }
      }
      decButton := Button
      {
        text = "decrement"
        onAction.add |Event e|
        {
          if (textField.text != "")
          {
            try
            {
              Int value := textField.text.toInt
              if (value > 0) value -= 1
              textField.text = value.toStr
            }
            catch {}
          }
        }
      }
      // add a listener for modifications to the text field
      // which updates the button visibilities
      textField.onModify.add |Event e|
      {
        try
        {
          Int value := textField.text.toInt
          incButton.enabled = (value < 10) // update whether button can be used
          decButton.enabled = (value > 0)  // update whether button can be used
        }
        catch textField.text = "0"  // reset if not an int
      }
      EdgePane
      {
        top = textField
        left = incButton
        right = decButton
      },
    }.open
  }
}


#Include "windows.bi"

Dim As HWND Window_Main, Edit_Number, Button_Inc, Button_Dec
Dim As MSG msg
Dim As Integer n
Dim As String text

'Create a window with an input field and two buttons:
Window_Main = CreateWindow("#32770", "GUI Enabling/Disabling of Controls", WS_OVERLAPPEDWINDOW Or WS_VISIBLE, 100, 100, 250, 200, 0, 0, 0, 0)
Var Static_Number = CreateWindow("STATIC", "Value:", WS_VISIBLE Or WS_CHILD, 10, 10, 100, 20, Window_Main, 0, 0, 0)
Edit_Number = CreateWindow("EDIT", "0", WS_BORDER Or WS_VISIBLE Or WS_CHILD Or ES_AUTOHSCROLL Or ES_Number, 110, 10, 100, 20, Window_Main, 0, 0, 0)
Button_Inc = CreateWindow("BUTTON", "Increment", WS_VISIBLE Or WS_CHILD, 110, 40, 100, 20, Window_Main, 0, 0, 0)
Button_Dec = CreateWindow("BUTTON", "Decrement", WS_VISIBLE Or WS_CHILD, 110, 70, 100, 20, Window_Main, 0, 0, 0)

'Windows message loop:
While GetMessage(@msg, Window_Main, 0, 0)
  text = Space(GetWindowTextLength(Edit_Number) + 1)	'Buffer for the text
  GetWindowText(Edit_Number, text, Len(text))
  n = Val(text)
  If n <> 0 Then EnableWindow(Edit_Number, False) Else EnableWindow(Edit_Number, True)
  If n > 9 Then EnableWindow(Button_Inc, False) Else EnableWindow(Button_Inc, True)
  If n > 0 Then EnableWindow(Button_Dec, True) Else EnableWindow(Button_Dec, False)
  TranslateMessage(@msg)
  DispatchMessage(@msg)
  Select Case msg.hwnd
    Case Button_Inc
      'Increment value:
      If msg.message = WM_LBUTTONDOWN Then SetWindowText(Edit_Number, Str(n + 1))
   Case Button_Dec
     'Decrement value:
     If msg.message = WM_LBUTTONDOWN Then SetWindowText(Edit_Number, Str(n - 1))
   Case Window_Main
    If msg.message = WM_COMMAND Then End
  End Select
Wend

End


hValueBox As ValueBox                                             'We need a ValueBox
hButton0 As Button                                                'We need a button
hButton1 As Button                                                'We need another button

Public Sub Form_Open()

With Me                                                           'Set the Form's Properties..
  .height = 95                                                    'Set the Height
  .Width = 350                                                    'Set the Width
  .Arrangement = Arrange.Vertical                                 'Arrange items vertically
  .Padding = 5                                                    'Border area
  .Title = "GUI enable/disable"                                   'Title displayed on the Form
End With

hValueBox = New ValueBox(Me) As "ValBox"                          'Add a ValueBox to the Form as Event 'ValBox'

With hValueBox                                                    'Set the ValueBox's Properties..
  .Expand = True                                                  'Expand the ValueBox
  .Value = 0                                                      'Set it's value to 0
End With

hButton0 = New Button(Me) As "ButtonInc"                          'Add a Button to the form as Event "ButtonInc"

With hButton0                                                     'Set the Button's Properties..
  .Height = 28                                                    'Set the Height
  .Text = "&Increment"                                            'Add Text (The '&' adds a keyboard shortcut)
End With

hButton1 = New Button(Me) As "ButtonDec"                          'Add a Button to the form as Event "ButtonDec"

With hButton1                                                     'Set the Button's Properties..
  .Height = 28                                                    'Set the Height
  .Text = "&Decrement"                                            'Add Text (The '&' adds a keyboard shortcut)
  .Enabled = False                                                'Disable the button
End With

End

Public Sub ButtonInc_Click()                                      'When the 'Increment' Button is clicked..

hValueBox.Value += 1                                              'Increase the Value in the ValueBox by 1
Checks

End

Public Sub ButtonDec_Click()                                      'When the 'Decrement' Button is clicked..

hValueBox.Value -= 1                                              'Increase the Value in the ValueBox by 1
Checks

End

Public Sub Checks()                                               'Checks the values to see which controls to en/disable

If hValueBox.Value = 0 Then                                       'If the ValueBox = 0 then..
  hValueBox.enabled = True                                        'Enable the control
Else                                                              'Else..
  hValueBox.enabled = False                                       'Disable the control
End If

If hValueBox.Value > 9 Then                                       'If the ValueBox greater than 9 then..
  hButton0.enabled = False                                        'Disable the control
Else                                                              'Else..
  hButton0.enabled = True                                         'Enable the control
End If

If hValueBox.Value < 1 Then                                       'If the ValueBox less than 1 then..
  hButton1.enabled = False                                        'Disable the control
Else                                                              'Else..
  hButton1.enabled = True                                         'Enable the control
End If

End

Public Sub ValBox_Leave()                                         'When the mouse leaves the ValueBox..

Checks                                                            'Rune the Checks routine

End


package main

import (
    "github.com/gotk3/gotk3/gtk"
    "log"
    "math/rand"
    "strconv"
    "time"
)

func validateInput(window *gtk.Window, str string) (int64, bool) {
    i, err := strconv.ParseInt(str, 10, 64)
    if err != nil {
        dialog := gtk.MessageDialogNew(
            window,
            gtk.DIALOG_MODAL,
            gtk.MESSAGE_ERROR,
            gtk.BUTTONS_OK,
            "Invalid value",
        )
        dialog.Run()
        dialog.Destroy()
        return 0, false
    }
    return i, true
}

func check(err error, msg string) {
    if err != nil {
        log.Fatal(msg, err)
    }
}

func processState(i int64, entry *gtk.Entry, ib, db *gtk.Button) {
    if i == 0 {
        entry.SetSensitive(true)
    } else {
        entry.SetSensitive(false)
    }
    if i < 10 {
        ib.SetSensitive(true)
    } else {
        ib.SetSensitive(false)
    }
    if i > 0 {
        db.SetSensitive(true)
    } else {
        db.SetSensitive(false)
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    gtk.Init(nil)

    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
    check(err, "Unable to create window:")
    window.SetTitle("Rosetta Code")
    window.SetPosition(gtk.WIN_POS_CENTER)
    window.Connect("destroy", func() {
        gtk.MainQuit()
    })

    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
    check(err, "Unable to create box:")
    box.SetBorderWidth(1)

    label, err := gtk.LabelNew("Value:")
    check(err, "Unable to create label:")

    entry, err := gtk.EntryNew()
    check(err, "Unable to create entry:")
    entry.SetText("0") // initialize to zero
    entry.SetSensitive(true)

    // button to increment
    ib, err := gtk.ButtonNewWithLabel("Increment")
    check(err, "Unable to create increment button:")
    ib.SetSensitive(true)

    // button to decrement
    db, err := gtk.ButtonNewWithLabel("Decrement")
    check(err, "Unable to create decrement button:")
    db.SetSensitive(false)

    entry.Connect("activate", func() {
        // read and validate the entered value
        str, _ := entry.GetText()
        i, ok := validateInput(window, str)
        if !ok {
            entry.SetText("0")
        }
        processState(i, entry, ib, db)
    })

    ib.Connect("clicked", func() {
        // read the entered value
        str, _ := entry.GetText()
        i, _ := validateInput(window, str)
        i++
        entry.SetText(strconv.FormatInt(i, 10))
        processState(i, entry, ib, db)
    })

    db.Connect("clicked", func() {
        // read the entered value
        str, _ := entry.GetText()
        i, _ := validateInput(window, str)
        i--
        entry.SetText(strconv.FormatInt(i, 10))
        processState(i, entry, ib, db)
    })

    box.PackStart(label, false, false, 2)
    box.PackStart(entry, false, false, 2)
    box.PackStart(ib, false, false, 2)
    box.PackStart(db, false, false, 2)
    window.Add(box)

    window.ShowAll()
    gtk.Main()
}


import gui
$include "guih.icn"

class MessageDialog : Dialog (message)
  method component_setup ()
    label := Label ("label="||message, "pos=20,20")
    add (label)
    button := TextButton("label=OK", "pos=100,60")
    button.connect (self, "dispose", ACTION_EVENT)
    add (button)

    connect (self, "dispose", CLOSE_BUTTON_EVENT)
    attrib ("size=200,100", "bg=light gray")
  end

  initially (message)
    self.Dialog.initially()
    self.message := message
end

class WindowApp : Dialog (button1, button2, field, value)
  method set_enabled ()
    if value = 0
      then field.clear_is_shaded ()
      else field.set_is_shaded ()
    if value <= 0
      then button2.set_is_shaded ()
      else button2.clear_is_shaded ()
    if value >= 10
      then button1.set_is_shaded ()
      else button1.clear_is_shaded ()
  end

  method increment ()
    value +:= 1
    field.set_contents (string(value))
    set_enabled ()
  end

  method decrement ()
    value -:= 1
    field.set_contents (string(value))
    set_enabled ()
  end

  method handle_text_field ()
    if not(integer(field.get_contents ()))
      then {
        warning := MessageDialog ("Not a number")
        warning.show_modal ()
        field.set_contents (string(value))
      }
      else {
        n := integer (field.get_contents ())
        if not (0 <= n <= 10)
          then {
            warning := MessageDialog ("Not in range")
            warning.show_modal ()
            field.set_contents (string(value))
          }
      }
    value := integer (field.get_contents ()) # must be ok
    set_enabled ()
  end

  method component_setup ()
    value := 0
    field := TextField("contents="||value, "pos=20,20", "size=150")
    field.connect (self, "handle_text_field", TEXTFIELD_CHANGED_EVENT)
    add (field)
    button1 := TextButton("label=Increment", "pos=20,60", "size=70")
    button1.connect (self, "increment", ACTION_EVENT)
    add (button1)
    button2 := TextButton("label=Decrement", "pos=100,60", "size=70")
    button2.connect (self, "decrement", ACTION_EVENT)
    add (button2)

    connect (self, "dispose", CLOSE_BUTTON_EVENT)
    attrib ("size=200,100", "bg=light gray")
    set_enabled ()
  end
end

procedure main ()
  w := WindowApp ()
  w.show_modal ()
end


task_run=: wd bind (noun define)
  pc task nosize;
  cc decrement button;cn "Decrement";
  cc increment button;cn "Increment";
  cc Value edit center;set Value text 0;
  set decrement enable 0;
  pas 6 6;pcenter;
  pshow;
)

task_cancel=: task_close=: wd bind 'pclose'

task_Value_button=: update=: verb define
  wd 'set Value text ', ": n=. {. 0 ". Value
  wd 'set Value enable ', ": n=0
  wd 'set increment enable ', ": n<10
  wd 'set decrement enable ', ": n>0
)

task_increment_button=:verb define
  update Value=: ": 1 + 0 ". Value
)

task_decrement_button=:verb define
  update Value=: ": _1 + 0 ". Value
)


import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Interact extends JFrame{
	final JTextField numberField;
	final JButton incButton, decButton;

	public Interact(){
		//stop the GUI threads when the user hits the X button
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		numberField = new JTextField();
		incButton = new JButton("Increment");
		decButton = new JButton("Decrement");

		numberField.setText("0");//start at 0
		decButton.setEnabled(false);//we're already at 0

		//listen for button presses in the text field
		numberField.addKeyListener(new KeyListener(){
			@Override
			public void keyTyped(KeyEvent e) {
				//if the entered character is not a digit
				if(!Character.isDigit(e.getKeyChar())){
					//eat the event (i.e. stop it from being processed)
					e.consume();
				}else if(Character.isDigit(e.getKeyChar())){
					//This method is executed from the event thread and updating the GUI
					//from there doesn't always work. invokeLater will ensure that the
					//GUI is updated
					SwingUtilities.invokeLater(new Runnable() {
						@Override
						public void run() {
							String text = numberField.getText();
							if(text.isEmpty()){//default to 0 when all text is erased
								numberField.setText("0");
								decButton.setEnabled(false);
								incButton.setEnabled(true);
								return;
							}
							if(Long.valueOf(text) <= 0){
								decButton.setEnabled(false);
								incButton.setEnabled(true);
							}else if(Long.valueOf(text) >= 10){
								incButton.setEnabled(false);
								decButton.setEnabled(true);
							}else{
								incButton.setEnabled(true);
								decButton.setEnabled(true);
							}
						}
					});
				}
			}
			@Override
			public void keyReleased(KeyEvent e){}
			@Override
			public void keyPressed(KeyEvent e){
				//backspace and delete don't register in keyTyped because they don't
				//display a Unicode character, so they must be handled here
				if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE ||
						e.getKeyCode() == KeyEvent.VK_DELETE){
					SwingUtilities.invokeLater(new Runnable() {
						@Override
						public void run() {
							String text = numberField.getText();
							if(text.isEmpty()){
								numberField.setText("0");
								decButton.setEnabled(false);
								incButton.setEnabled(true);
								return;
							}
							if(Long.valueOf(text) <= 0){
								decButton.setEnabled(false);
								incButton.setEnabled(true);
							}else if(Long.valueOf(text) >= 10){
								incButton.setEnabled(false);
								decButton.setEnabled(true);
							}else{
								incButton.setEnabled(true);
								decButton.setEnabled(true);
							}
						}
					});
				}
			}
		});

		//listen for button clicks on the increment button
		incButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				String text = numberField.getText();
				numberField.setText((Long.valueOf(text) + 1) + "");
				if(Long.valueOf(text) + 1 >= 10){
					incButton.setEnabled(false);
				}

				if(Long.valueOf(text) + 1 > 0){
					decButton.setEnabled(true);
				}
			}
		});

		//listen for button clicks on the random button
		decButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				String text = numberField.getText();
				numberField.setText((Long.valueOf(text) - 1) + "");
				if(Long.valueOf(text) - 1 <= 0){
					decButton.setEnabled(false);
				}

				if(Long.valueOf(text) - 1 < 10){
					incButton.setEnabled(true);
				}
			}
		});

		//arrange the components in a grid with 2 rows and 1 column
		setLayout(new GridLayout(2, 1));

		//a secondary panel for arranging both buttons in one grid space in the window
		JPanel buttonPanel = new JPanel();

		//the buttons are in a grid with 1 row and 2 columns
		buttonPanel.setLayout(new GridLayout(1, 2));
		//add the buttons
		buttonPanel.add(incButton);
		buttonPanel.add(decButton);

		//put the number field on top of the buttons
		add(numberField);
		add(buttonPanel);
		//size the window appropriately
		pack();

	}

	public static void main(String[] args){
		new Interact().setVisible(true);
	}
}


using Tk
w = Toplevel("GUI enabling/disabling")
fr = Frame(w)
pack(fr, {:expand=>true, :fill => "both"})

value = Entry(fr)
increment = Button(fr, "+")
decrement = Button(fr, "-")

formlayout(value, "Value:")
formlayout(increment, " ")
formlayout(decrement, " ")

## value stores a string
set_value(value, "0") ## The field is initialized to zero.
get(value::Tk_Entry) = try parseint(get_value(value)) catch e nothing end

function update()
    cur_value = get(value)
    set_enabled(value,     isa(cur_value, Integer) && cur_value == 0)
    set_enabled(increment, isa(cur_value, Integer) && cur_value < 10)
    set_enabled(decrement, isa(cur_value, Integer) && cur_value > 0)
end

crement = function(step)
  set_enabled(value, true)
  set_value(value, string(get(value) + step))
  update()
end
tk_bind(increment, "command", path -> crement(1))
tk_bind(decrement, "command", path -> crement(-1))
update()

function validate_command(path, P)
    try
        if length(P) > 0 parseint(P); update() end
        tcl("expr", "TRUE")
    catch e
        tcl("expr", "FALSE")
    end
end
function invalid_command(path, W)
    println("Invalid value")
    tcl(W, "delete", "@0", "end")
end

tk_configure(value, {:validate=>"focusout", :validatecommand=>validate_command, :invalidcommand=>invalid_command })


// version 1.2.21

import javafx.application.Application
import javafx.beans.property.SimpleLongProperty
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.control.TextField
import javafx.scene.layout.HBox
import javafx.scene.layout.VBox
import javafx.stage.Stage
import javafx.util.converter.NumberStringConverter
import javafx.event.ActionEvent

val digits = Regex("[0-9]*")

class InteractFX : Application() {

    override fun start(stage: Stage) {
        val input = object : TextField("0") {
            // only accept numbers as input
            override fun replaceText(start: Int, end: Int, text: String) {
                if (text.matches(digits)) super.replaceText(start, end, text)
            }

            // only accept numbers on copy + paste
            override fun replaceSelection(text: String) {
                if (text.matches(digits)) super.replaceSelection(text)
            }
        }

        // when the textfield is empty, replace text with "0"
        input.textProperty().addListener { _, _, newValue ->
            if (newValue == null || newValue.trim().isEmpty()) input.text = "0"
        }

        // get a bi-directional bound long-property of the input value
        val inputValue = SimpleLongProperty()
        input.textProperty().bindBidirectional(inputValue, NumberStringConverter())

        // textfield is disabled when the current value is other than "0"
        input.disableProperty().bind(inputValue.isNotEqualTo(0))

        val increment = Button("Increment")
        increment.addEventHandler(ActionEvent.ACTION) { inputValue.set(inputValue.get() + 1) }

        // increment button is disabled when input is >= 10
        increment.disableProperty().bind(inputValue.greaterThanOrEqualTo(10))

        val decrement = Button("Decrement")
        decrement.addEventHandler(ActionEvent.ACTION) { inputValue.set(inputValue.get() - 1) }

        // decrement button is disabled when input is <= 0
        decrement.disableProperty().bind(inputValue.lessThanOrEqualTo(0))

        // layout
        val root = VBox()
        root.children.add(input)
        val buttons = HBox()
        buttons.children.addAll(increment, decrement)
        root.children.add(buttons)

        stage.scene = Scene(root)
        stage.sizeToScene()
        stage.show()
    }
}

fun main(args: Array<String>) {
    Application.launch(InteractFX::class.java, *args)
}


nomainwin
    textbox #demo.val, 20, 50, 90, 24
    button #demo.dec, "Decrement", [btnDecrement], UL, 20, 90, 90, 24
    button #demo.inc, "Increment", [btnIncrement], UL, 20, 120, 90, 24
    statictext #demo.txt, "Positive or negative whole numbers only.", 20, 170, 240, 24
    open "Rosetta Task: GUI enabling/disabling of controls" for window as #demo
    #demo "trapclose [quit]"
    #demo.val 0
    #demo.dec "!disable"
wait

[quit]
    close #demo
end

[btnDecrement]
    validNum = validNum()
    if validNum = 0 then
        #demo.val "!contents? nVal$"
        notice nVal$;" does not appear to be a valid whole number."
    else
        #demo.val "!contents? nVal"
        if nVal > 0 then
            nVal = nVal - 1
        end if
    end if
    #demo.val nVal
    call disEnableControls nVal
wait

[btnIncrement]
    validNum = validNum()
    if validNum = 0 then
        #demo.val "!contents? nVal$"
        notice nVal$;" does not appear to be a valid whole number."
    else
        #demo.val "!contents? nVal"
        if nVal < 10 then
            nVal = nVal + 1
        end if
    end if
    #demo.val nVal
    call disEnableControls nVal
wait

Function validNum()
    validNum$ = "0123456789"
    #demo.val "!contents? nVal$"
    nVal$ = trim$(nVal$)
    if left$(nVal$, 1) = "-" then
        neg = 1
        nVal$ = mid$(nVal$, 2)
    else
        neg = 0
    end if
    validNum = 1
    for i = 1 to len(nVal$)
        if instr(validNum$, mid$(nVal$, i, 1)) = 0 then
            validNum = 0
        end if
    next i
End Function

Sub disEnableControls nVal
    if nVal > 9 then
        #demo.inc "!disable"
    else
        #demo.inc "!enable"
    end if
    if nVal < 1 then
        #demo.dec "!disable"
    else
        #demo.dec "!enable"
    end if
    if nVal = 0 then
        #demo.val "!enable"
    else
        #demo.val "!disable"
    end if
End Sub


command enableButtons v
    switch
        case v <= 0
            put 0 into fld "Field1"
            set the enabled of btn "Button1" to true
            set the enabled of btn "Button2" to false
            break
        case v >= 10
            put 10 into fld "Field1"
            set the enabled of btn "Button1" to false
            set the enabled of btn "Button2" to true
            break
        default
            set the enabled of btn "Button1" to true
            set the enabled of btn "Button2" to true
            put v into fld "Field1"
    end switch
end enableButtons


\\ this is global, but call as local in events, which means with local visibility for identifiers
\\ so thispos and this$ has to exist in caller 's context

Function Global Local1(new Feed$) {
            \\ this function can be used from other Integer
            \\ this$ and thispos, exist just before the call of this function
            local sgn$
            if feed$="" and this$="-" then thispos-- :  exit
            if left$(this$,1)="-" then sgn$="-": this$=mid$(this$, 2)
            if this$<>Trim$(this$)  then  this$=Feed$ :  thispos-- : exit
            If Trim$(this$)="" then this$="0" : thispos=2 : exit
            if instr(this$,"+")>0 and sgn$="-" then this$=filter$(this$, "+") : sgn$=""
            if instr(this$,"-")>0  and sgn$="" then this$=filter$(this$, "-") : sgn$="-"
            if filter$(this$,"0123456789")<>"" then this$=Feed$ :  thispos-- : exit
            if len(this$)>1 then While  left$(this$,1)="0" {this$=mid$(this$, 2)}
            this$=sgn$+this$
            if this$="-0" then this$="-" : thispos=2
        }
Module CheckIt {
      Declare form1 form
      Declare textbox1 textbox form form1
      Declare buttonInc Button form form1
      Declare buttonDec Button form form1
      Method textbox1, "move", 2000,2000,4000,600
      Method buttonInc, "move", 2000,3000,2000,600
      Method buttonDec, "move", 4000,3000,2000,600
      With textbox1,"vartext" as textbox1.value$, "Prompt", "Value:" ', "ShowAlways", True
      With buttonInc,"Caption","Increment"
      With buttonDec,"Caption","Decrement","Locked", True
      textbox1.value$="0"

      Function controlIncDec(what$){
            With buttonInc, "locked",  not val(what$)<10
            With buttonDec, "locked", not val(what$)>0
      }
      finishEnter=false
      Function TextBox1.ValidString {
                  \\ this function called direct from textbox
                  Read  New &this$, &thispos
                  Call Local local1(textbox1.value$)
                  Call Local controlIncDec(this$)
      }
      Function TextBox1.Enable {
            With TextBox1, "Enabled", true
            finishEnter=false
      }
      Function TextBox1.Disable {
            With TextBox1, "Enabled", false
            finishEnter=true
      }
      Function TextBox1.Enter {
            Call Local TextBox1.Disable()
      }
      Function buttonInc.Click {
                if  not finishEnter then Call Local TextBox1.Disable()
               textbox1.value$=str$(val(textbox1.value$)+1, "")
                if val(textbox1.value$)=0 then Call Local TextBox1.Enable()
      }
      function buttonDec.Click {
                if  not finishEnter then Call Local TextBox1.Disable()
                textbox1.value$=str$(val(textbox1.value$)-1, "")
                if val(textbox1.value$)=0 then Call Local TextBox1.Enable()
      }
      Call Local controlIncDec(textBox1.Value$)
      Method form1, "show", 1
      Declare form1 nothing
}
Checkit


Manipulate[Null, {{value, 0},
  InputField[Dynamic[value], Number,
    Enabled -> Dynamic[value == 0]] &},
 [email protected]{Button["increment", value++, Enabled -> Dynamic[value < 10]],
   Button["decrement", value--, Enabled -> Dynamic[value > 0]]}]