package require Thread

foreach name {Aristotle Kant Spinoza Marx Russel} {
    lappend forks [thread::mutex create]
    lappend tasks [set t [thread::create -preserved {
        # Implement each task as a coroutine internally for simplicity of presentation
        # This is because we want to remain able to receive messages so we can shut
        # down neatly at the end of the program.
	interp alias {} doTask {} coroutine t philosopher
	proc delay {expression} {
	    yield [after [expr $expression] [info coroutine]]
	}

        # Forks are mutexes...
        proc pickUpFork fork {
            thread::mutex lock $fork
        }
        proc putDownFork fork {
            thread::mutex unlock $fork
        }

        # The actual implementation of the task
	proc philosopher {f1 f2} {
	    global name
	    # Always acquire forks in order; prevents deadlock
            # Uses the "natural" order of the lexicographical order of the fork names
	    if {$f1 > $f2} {
                lassign [list $f1 $f2] f2 f1
            }

            # The classic "philosophers" loop
	    while {true} {
		puts "$name is thinking"
		delay {int(200*rand())}

		puts "$name is hungry, getting fork in left hand"
		pickUpFork $f1
		delay {int(2000*rand())} ;# Make deadlock likely if it is possible!

		puts "$name is hungry, getting fork in right hand"
		pickUpFork $f2

		puts "$name is eating"
		delay {int(2000*rand())}

		puts "$name has finished eating; putting down forks"
		putDownFork $f2
		putDownFork $f1
                delay 100
	    }
	}
	thread::wait
    }]]
    thread::send $t [list set name $name]
}

# Set the tasks going
foreach t $tasks {f1 f2} {0 1 1 2 2 3 3 4 4 0} {
    thread::send -async $t [list \
            doTask [lindex $forks $f1] [lindex $forks $f2]]
}

# Kill everything off after 30 seconds; that's enough for demonstration!
after 30000
puts "Completing..."
foreach t $tasks {
    thread::send -async $t thread::exit
}


begin

    % determnines whether the string contains an integer, real or imaginary  %
    % number. Returns true if it does, false otherwise                       %
    logical procedure isNumeric( string(32) value text ) ;
        begin

            logical ok;
            % the "number" cannot be blank                                   %
            ok := ( text not = " " );
            if ok then begin

                % there is at least one non-blank character                  %
                % must have either an integer or real/immaginary number      %
                % integer: [+|-]digit-sequence                               %
                % real:    [+|-][digit-sequence].digit-sequence['integer][L] %
                % or:      [+|-]digit-sequence[.[digit-sequence]]'integer[L] %
                % imaginary:                                                 %
                %          [+|-][digit-sequence].digit-sequence['integer][L]I%
                % or:      [+|-]digit-sequence[.[digit-sequence]]'integer[L]I%
                % The "I" at the end of an imaginary number can appear       %
                % before or after the "L" (which indicates a long number)    %
                % the "I" and "L" can be in either case                      %

                procedure nextChar ; charPos := charPos + 1;
                logical procedure have( string(1) value ch ) ;
                    ( charPos <= maxChar and text(charPos//1) = ch ) ;

                logical procedure haveDigit ;
                    ( charPos <= maxChar and text(charPos//1) >= "0" and text(charPos//1) <= "9" ) ;

                integer charPos, maxChar;
                logical hadDigits, isReal;
                charPos   :=  0;
                maxChar   := 31;
                hadDigits := false;
                isReal    := false;

                % skip trailing spaces                                       %
                while maxChar > 0 and text(maxChar//1) = " " do maxChar := maxChar - 1;
                % skip leading spacesx                                       %
                while have( " " ) do nextChar;

                % skip optional sign                                         %
                if have( "+" ) or have( "-" ) then nextChar;

                if      haveDigit then begin
                    % have a digit sequence                                  %
                    hadDigits := true;
                    while haveDigit do nextChar
                end if_have_sign ;

                if have( "." ) then begin
                    % real or imaginary number                               %
                    nextChar;
                    isReal    := true;
                    hadDigits := hadDigits or haveDigit;
                    while haveDigit do nextChar
                end if_have_point ;

                % should have had some digits                                %
                ok := hadDigits;

                if ok and have( "'" ) then begin
                    % the number has an exponent                             %
                    isReal := true;
                    nextChar;
                    % skip optional sign                                     %
                    if have( "+" ) or have( "-" ) then nextChar;
                    % must have a digit sequence                             %
                    ok := haveDigit;
                    while haveDigit do nextChar;
                end if_ok_and_have_exponent ;

                % if it is a real number, there could be L/I suffixes        %
                if ok and isReal then begin
                    integer LCount, ICount;
                    LCount := 0;
                    ICount := 0;
                    while have( "L" ) or have( "l" ) or have( "I" ) or have( "i" ) do begin
                        if have( "L" ) or have( "l" )
                        then LCount := LCount + 1
                        else ICount := ICount + 1;
                        nextChar
                    end while_have_L_or_I ;
                    % there can be at most one L and at most 1 I             %
                    ok := ( LCount < 2 and ICount < 2 )
                end if_ok_and_isReal ;

                % must now be at the end if the number                       %
                ok := ok and charPos >= maxChar

            end if_ok ;

            ok
        end isNumeric ;

    % test the isNumeric procedure                                           %
    procedure testIsNumeric( string(32) value n
                           ; logical    value expectedResult
                           ) ;
        begin
            logical actualResult;
            actualResult := isNumeric( n );
            write( s_w := 0
                 , """", n, """ is "
                 , if actualResult then "" else "not "
                 , "numeric "
                 , if actualResult = expectedResult then "" else " NOT "
                 , "as expected"
                 )
        end testIsNumeric ;

    testIsNumeric(          "", false );
    testIsNumeric(         "b", false );
    testIsNumeric(         ".", false );
    testIsNumeric(       ".'3", false );
    testIsNumeric(       "3.'", false );
    testIsNumeric(    "0.0z44", false );
    testIsNumeric(      "-1IL", false );
    testIsNumeric( "4.5'23ILL", false );

    write( "---------" );

    testIsNumeric(        "-1", true  );
    testIsNumeric(    " +.345", true  );
    testIsNumeric(   "4.5'23I", true  );
    testIsNumeric(    "-5'+3i", true  );
    testIsNumeric(    "-5'-3l", true  );
    testIsNumeric(  " -.345LI", true  );

end.


String numericString = '123456';
String partlyNumericString = '123DMS';
String decimalString = '123.456';

System.debug(numericString.isNumeric()); // this will be true
System.debug(partlyNumericString.isNumeric()); // this will be false
System.debug(decimalString.isNumeric()); // this will be false
System.debug(decimalString.remove('.').isNumeric()); // this will be true


/*REXX program "squeezes" all immediately repeated characters in a string (or strings). */
@.=                                              /*define a default for the  @.  array. */
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3=  ..1111111111111111111111111111111111111111111111111111111111111117777888
#.4=  . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
#.5= ' '; @.5= '                                                   ---  Harry S Truman  '
#.6= '-'; @.6= @.5
#.7= 'r'; @.7= @.5

     do j=1;    L= length(@.j)                   /*obtain the length of an array element*/
     say copies('═', 105)                        /*show a separator line between outputs*/
     if j>1  &  L==0     then leave              /*if arg is null and  J>1, then leave. */
     say '    specified immediate repeatable character='     #.j      "   ('"c2x(#.j)"'x)"
     say '    length='right(L, 3)     "   input=«««" || @.j || '»»»'
     new= squeeze(@.j, #.j)
       w= length(new)
     say '    length='right(w, 3)     "  output=«««" || new || '»»»'
     end   /*j*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
squeeze: procedure; parse arg y 1 $ 2,z          /*get string; get immed. repeated char.*/
         if pos(z || z, y)==0  then return y     /*No repeated immediate char?  Return Y*/
                                                 /* [↑]  Not really needed;  a speed─up.*/
                     do k=2  to length(y)        /*traipse through almost all the chars.*/
                     _= substr(y, k, 1)                      /*pick a character from  Y */
                     if _==right($, 1) & _==z then iterate   /*Same character?  Skip it.*/
                     $= $ || _                               /*append char., it's diff. */
                     end     /*j*/
         return $


strings = ["",
        '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                   ---  Harry S Truman  ",
        "😍😀🙌💃😍😍😍🙌",]
squeeze_these = ["", "-", "7", ".", " -r", "😍"]

strings.zip(squeeze_these).each do |str, st|
  puts "original:     «««#{str}»»» (size #{str.size})"
  st.chars.each do |c|
    ssq = str.squeeze(c)
    puts "#{c.inspect}-squeezed: «««#{ssq}»»» (size #{ssq.size})"
  end
  puts
end


'The combination of holding to the second fork
'(HOLDON=True) and all philosophers start
'with same hand (DIJKSTRASOLUTION=False) leads
'to a deadlock. To prevent deadlock
'set HOLDON=False, and DIJKSTRASOLUTION=True.
Public Const HOLDON = False
Public Const DIJKSTRASOLUTION = True
Public Const X = 10 'chance to continue eating/thinking
Public Const GETS = 0
Public Const PUTS = 1
Public Const EATS = 2
Public Const THKS = 5
Public Const FRSTFORK = 0
Public Const SCNDFORK = 1
Public Const SPAGHETI = 0
Public Const UNIVERSE = 1
Public Const MAXCOUNT = 100000
Public Const PHILOSOPHERS = 5
Public semaphore(PHILOSOPHERS - 1) As Integer
Public positi0n(1, PHILOSOPHERS - 1) As Integer
Public programcounter(PHILOSOPHERS - 1) As Long
Public statistics(PHILOSOPHERS - 1, 5, 1) As Long
Public names As Variant
Private Sub init()
    names = [{"Aquinas","Babbage","Carroll","Derrida","Erasmus"}]
    For j = 0 To PHILOSOPHERS - 2
        positi0n(0, j) = j + 1 'first fork in right hand
        positi0n(1, j) = j     'second fork in left hand
    Next j
    If DIJKSTRASOLUTION Then
        positi0n(0, PHILOSOPHERS - 1) = j '  first fork in left hand
        positi0n(1, PHILOSOPHERS - 1) = 0 'second fork in right hand
    Else
        positi0n(0, PHILOSOPHERS - 1) = 0 'first fork in right hand
        positi0n(1, PHILOSOPHERS - 1) = j 'second fork in left hand
    End If
End Sub
Private Sub philosopher(subject As Integer, verb As Integer, objekt As Integer)
    statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1
    If verb < 2 Then
        If semaphore(positi0n(objekt, subject)) <> verb Then
            If Not HOLDON Then
                'can't get a fork, release first fork if subject has it, and
                'this won't toggle the semaphore if subject hasn't firt fork
                semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt
                'next round back to try to get first fork
                programcounter(subject) = 0
            End If
        Else
            'just toggle semaphore and move on
            semaphore(positi0n(objekt, subject)) = 1 - verb
            programcounter(subject) = (programcounter(subject) + 1) Mod 6
        End If
    Else
        'when eating or thinking, (100*(X-1)/X)% continue eating or thinking
        '(100/X)% advance program counter
        programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6
    End If
End Sub
Private Sub dine()
    Dim ph As Integer
    Do While TC < MAXCOUNT
        For ph = 0 To PHILOSOPHERS - 1
            Select Case programcounter(ph)
                Case 0: philosopher ph, GETS, FRSTFORK
                Case 1: philosopher ph, GETS, SCNDFORK
                Case 2: philosopher ph, EATS, SPAGHETI
                Case 3: philosopher ph, PUTS, FRSTFORK
                Case 4: philosopher ph, PUTS, SCNDFORK
                Case 5: philosopher ph, THKS, UNIVERSE
            End Select
            TC = TC + 1
        Next ph
    Loop
End Sub
Private Sub show()
    Debug.Print "Stats", "Gets", "Gets", "Eats", "Puts", "Puts", "Thinks"
    Debug.Print "", "First", "Second", "Spag-", "First", "Second", "About"
    Debug.Print "", "Fork", "Fork", "hetti", "Fork", "Fork", "Universe"
    For subject = 0 To PHILOSOPHERS - 1
        Debug.Print names(subject + 1),
        For objekt = 0 To 1
            Debug.Print statistics(subject, GETS, objekt),
        Next objekt
        Debug.Print statistics(subject, EATS, SPAGHETI),
        For objekt = 0 To 1
            Debug.Print statistics(subject, PUTS, objekt),
        Next objekt
        Debug.Print statistics(subject, THKS, UNIVERSE)
    Next subject
End Sub
Public Sub main()
    init
    dine
    show
End Sub


-- isNumString :: String -> Bool
on isNumString(s)
    try
        if class of s is string then
            set c to class of (s as number)
            c is real or c is integer
        else
            false
        end if
    on error
        false
    end try
end isNumString

-- TEST
on run

    map(isNumString, {3, 3.0, 3.5, "3.5", "3E8", "-3.5", "30", "three", three, four})

    --> {false, false, false, true, true, true, true, false, false, false}

end run

-- three :: () -> Int
script three
    3
end script

-- four :: () -> Int
on four()
    4
end four

-- GENERIC FUNCTIONS FOR TEST

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to lambda(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property lambda : f
        end script
    end if
end mReturn


fn squeezable_string<'a>(s: &'a str, squeezable: char) -> impl Iterator<Item = char> + 'a {
    let mut previous = None;

    s.chars().filter(move |c| match previous {
        Some(p) if p == squeezable && p == *c => false,
        _ => {
            previous = Some(*c);
            true
        }
    })
}

fn main() {
    fn show(input: &str, c: char) {
        println!("Squeeze: '{}'", c);
        println!("Input ({} chars): \t{}", input.chars().count(), input);
        let output: String = squeezable_string(input, c).collect();
        println!("Output ({} chars): \t{}", output.chars().count(), output);
        println!();
    }

    let harry = r#"I never give 'em hell, I just tell the truth, and they think it's hell.
    ---  Harry S Truman"#;

    #[rustfmt::skip]
    let inputs = [
        ("", ' '),
        (r#""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln "#, '-'),
        ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'),
        (harry, ' '),
        (harry, '-'),
        (harry, 'r'),
        ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e'),
        ("headmistressship", 's'),
    ];

    inputs.iter().for_each(|(input, c)| show(input, *c));
}


func squeeze(str, c) {
    str.gsub(Regex("(" + c.escape + ")" + '\1+'), {|s1| s1 })
}

var strings = ["",
        '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                   ---  Harry S Truman  ",
        "😍😀🙌💃😍😍😍🙌"]

var squeeze_these = ["", "-", "7", ".", " -r", "😍"]

[strings, squeeze_these].zip {|str,st|
    say "    original: «««#{str}»»» (length: #{str.len})"
    st.each {|c|
        var ssq = squeeze(str, c)
        say "'#{c}'-squeezed: «««#{ssq}»»» (length: #{ssq.len})"
    }
    say ''
}


# Set test data as a list pairing even and odd values
# as test string and squeeze character(s) respectively.
set test {
    {} {" "}
    {"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln } {"-"}
    {..1111111111111111111111111111111111111111111111111111111111111117777888} {"7"}
    {I never give 'em hell, I just tell the truth, and they think it's hell. } {"."} ;# '
    {                                                    --- Harry S Truman  } {" " "-" "r"}
    {The better the 4-wheel drive, the further you'll be from help when ya get stuck!} {"e"} ;# '
    {headmistressship} {"s"}
}

foreach {str chrs} $test {
    foreach c $chrs {
        # Escape non-word replacement characters (such as .)
        set c [regsub -all {\W} $c {\\&}]

        # Uses regexp lookbehind to detect repeated characters
        set re [subst -noback {($c)(\1+)}] ;# build expression
        set sub [regsub -all $re $str {\1}]

        # Output
        puts [format "Original (length %3d): %s" [string length $str] $str]
        puts [format "Subbed   (length %3d): %s" [string length $sub] $sub]
        puts ----------------------
    }
}


Imports System.Threading
Module Module1
   Public rnd As New Random

   Sub Main()
       'Aristotle, Kant, Spinoza, Marx, and Russel
       Dim f1 As New Fork(1)
       Dim f2 As New Fork(2)
       Dim f3 As New Fork(3)
       Dim f4 As New Fork(4)
       Dim f5 As New Fork(5)

       Console.WriteLine("1: Deadlock")
       Console.WriteLine("2: Live lock")
       Console.WriteLine("3: Working")
       Select Console.ReadLine
           Case "1"
               Using _
                   Aristotle As New SelfishPhilosopher("Aristotle", f1, f2), _
                   Kant As New SelfishPhilosopher("Kant", f2, f3), _
                   Spinoza As New SelfishPhilosopher("Spinoza", f3, f4), _
                   Marx As New SelfishPhilosopher("Marx", f4, f5), _
                   Russel As New SelfishPhilosopher("Russel", f5, f1)

                   Console.ReadLine()
               End Using
           Case "2"
               Using _
                   Aristotle As New SelflessPhilosopher("Aristotle", f1, f2), _
                   Kant As New SelflessPhilosopher("Kant", f2, f3), _
                   Spinoza As New SelflessPhilosopher("Spinoza", f3, f4), _
                   Marx As New SelflessPhilosopher("Marx", f4, f5), _
                   Russel As New SelflessPhilosopher("Russel", f5, f1)

                   Console.ReadLine()
               End Using
           Case "3"
               Using _
                   Aristotle As New WisePhilosopher("Aristotle", f1, f2), _
                   Kant As New WisePhilosopher("Kant", f2, f3), _
                   Spinoza As New WisePhilosopher("Spinoza", f3, f4), _
                   Marx As New WisePhilosopher("Marx", f4, f5), _
                   Russel As New WisePhilosopher("Russel", f5, f1)

                   Console.ReadLine()
               End Using
       End Select
   End Sub

End Module


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

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

.equ BUFFERSIZE,          100

/* Initialized data */
.data
szMessNum: .asciz "Enter number : \n"

szMessError:            .asciz "String is not a number !!!\n"
szMessInteger:          .asciz "String is a integer.\n"
szMessFloat:            .asciz "String is a float.\n"
szMessFloatExp:         .asciz "String is a float with exposant.\n"
szCarriageReturn:       .asciz "\n"

/* UnInitialized data */
.bss
sBuffer:              .skip BUFFERSIZE

/*  code section */
.text
.global main
main:

loop:
    ldr r0,iAdrszMessNum
    bl affichageMess
    mov r0,#STDIN                               @ Linux input console
    ldr r1,iAdrsBuffer                          @ buffer address
    mov r2,#BUFFERSIZE                          @ buffer size
    mov r7, #READ                               @ request to read datas
    swi 0                                       @ call system
    ldr r1,iAdrsBuffer                          @ buffer address
    mov r2,#0                                   @ end of string
    sub r0,#1                                   @ replace character 0xA
    strb r2,[r1,r0]                             @ store byte at the end of input string (r0 contains number of characters)
    ldr r0,iAdrsBuffer
    bl controlNumber                            @ call routine
    cmp r0,#0
    bne 1f
    ldr r0,iAdrszMessError                      @ not a number
    bl affichageMess
    b 5f
1:
    cmp r0,#1
    bne 2f
    ldr r0,iAdrszMessInteger                    @ integer
    bl affichageMess
    b 5f
2:
    cmp r0,#2
    bne 3f
    ldr r0,iAdrszMessFloat                      @ float
    bl affichageMess
    b 5f
3:
    cmp r0,#3
    bne 5f
    ldr r0,iAdrszMessFloatExp                   @ float with exposant
    bl affichageMess
5:
    b loop

100:                                            @ standard end of the program
    mov r0, #0                                  @ return code
    mov r7, #EXIT                               @ request to exit program
    svc 0                                       @ perform system call
iAdrszMessNum:            .int szMessNum
iAdrszMessError:          .int szMessError
iAdrszMessInteger:        .int szMessInteger
iAdrszMessFloat:          .int szMessFloat
iAdrszMessFloatExp:       .int szMessFloatExp
iAdrszCarriageReturn:     .int szCarriageReturn
iAdrsBuffer:              .int sBuffer
/******************************************************************/
/*     control if string is number                          */
/******************************************************************/
/* r0 contains the address of the string */
/* r0 return 0 if not a number       */
/* r0 return 1 if integer   eq 12345 or -12345      */
/* r0 return 2 if float     eq 123.45 or 123,45  or -123,45     */
/* r0 return 3 if float with exposant  eq 123.45E30 or -123,45E-30        */
controlNumber:
    push {r1-r4,lr}                       @ save  registers
    mov r1,#0
    mov r3,#0          @ point counter
1:
    ldrb r2,[r0,r1]
    cmp r2,#0
    beq 5f
    cmp r2,#' '
    addeq r1,#1
    beq   1b
    cmp r2,#'-'                    @ negative ?
    addeq r1,#1
    beq 2f
    cmp r2,#'+'                    @ positive ?
    addeq r1,#1
2:
    ldrb r2,[r0,r1]                @ control space
    cmp r2,#0                      @ end ?
    beq 5f
    cmp r2,#' '
    addeq r1,#1
    beq 2b
3:
    ldrb r2,[r0,r1]
    cmp r2,#0                 @ end ?
    beq 10f
    cmp r2,#'E'               @ exposant ?
    beq 6f
    cmp r2,#'e'               @ exposant ?
    beq 6f
    cmp r2,#'.'               @ point ?
    addeq r3,#1               @ yes increment counter
    addeq r1,#1
    beq 3b
    cmp r2,#','               @ comma ?
    addeq r3,#1               @ yes increment counter
    addeq r1,#1
    beq 3b
    cmp r2,#'0'               @ control digit < 0
    blt 5f
    cmp r2,#'9'               @ control digit > 0
    bgt 5f
    add r1,#1                 @ no error loop digit
    b 3b
5:                            @ error detected
    mov r0,#0
    b 100f
6:    @ float with exposant
    add r1,#1
    ldrb r2,[r0,r1]
    cmp r2,#0             @ end ?
    moveq r0,#0           @ error
    beq 100f
    cmp r2,#'-'           @ negative exposant ?
    addeq r1,#1
    mov r4,#0             @ nombre de chiffres
7:
    ldrb r2,[r0,r1]
    cmp r2,#0             @ end ?
    beq 9f
    cmp r2,#'0'           @ control digit < 0
    blt 8f
    cmp r2,#'9'           @ control digit > 0
    bgt 8f
    add r1,#1
    add r4,#1             @ counter digit
    b 7b
8:
    mov r0,#0
    b 100f
9:
    cmp r4,#0             @ number digit exposant = 0 -> error
    moveq r0,#0           @ erreur
    beq 100f
    cmp r4,#2             @ number digit exposant > 2 -> error
    movgt r0,#0           @ error
    bgt 100f
    mov r0,#3             @ valid float with exposant
    b 100f
10:
    cmp r3,#0
    moveq r0,#1           @ valid integer
    beq 100f
    cmp r3,#1             @ number of point or comma = 1 ?
    moveq r0,#2           @ valid float
    movgt r0,#0           @ error
100:
    pop {r1-r4,lr}                         @ restaur des  2 registres
    bx lr                                        @ return
/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                       @ save  registers
    mov r2,#0                                   @ counter length */
1:                                              @ loop length calculation
    ldrb r1,[r0,r2]                             @ read octet start position + index
    cmp r1,#0                                   @ if 0 its over
    addne r2,r2,#1                              @ else add 1 in the length
    bne 1b                                      @ and loop
                                                @ so here r2 contains the length of the message
    mov r1,r0                                   @ address message in r1
    mov r0,#STDOUT                              @ code to write to the standard output Linux
    mov r7, #WRITE                              @ code call system "write"
    svc #0                                      @ call system
    pop {r0,r1,r2,r7,lr}                        @ restaur registers
    bx lr                                       @ return


Imports System.Linq.Enumerable

Module Module1

    Function Squeeze(s As String, c As Char) As String
        If String.IsNullOrEmpty(s) Then
            Return ""
        End If
        Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray())
    End Function

    Sub SqueezeAndPrint(s As String, c As Char)
        Console.WriteLine("squeeze: '{0}'", c)
        Console.WriteLine("old: {0} «««{1}»»»", s.Length, s)
        s = Squeeze(s, c)
        Console.WriteLine("new: {0} «««{1}»»»", s.Length, s)
    End Sub

    Sub Main()
        Const QUOTE = """"

        SqueezeAndPrint("", " ")
        SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-")
        SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
        SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")

        Dim s = "                                                    --- Harry S Truman  "
        SqueezeAndPrint(s, " ")
        SqueezeAndPrint(s, "-")
        SqueezeAndPrint(s, "r")
    End Sub

End Module


// Returns squeezed string, original and new lengths in
// unicode code points (not normalized).
fn squeeze(s string, c string) (string, int, int) {
    mut r := s.runes()
    mut t := c.runes()[0]
    le, mut del := r.len, 0
    for i := le - 2; i >= 0; i-- {
        if r[i] == t && r[i] == r[i+1] {
            r.delete(i)
            del++
        }
    }
    if del == 0 {
        return s, le, le
    }
    r = r[..le-del]
    return r.string(), le, r.len
}

fn main() {
    strings := [
        "",
        '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                   ---  Harry S Truman  ",
        "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
        "headmistressship",
        "aardvark",
        "😍😀🙌💃😍😍😍🙌",
	]
    chars := [[' '], ['-'], ['7'], ['.'], [' ', '-', 'r'], ['e'], ['s'], ['a'], ['😍']]

    for i, s in strings {
        for c in chars[i] {
            ss, olen, slen := squeeze(s, c)
            println("specified character = $c")
            println("original : length = ${olen:2}, string = «««$s»»»")
            println("squeezed : length = ${slen:2}, string = «««$ss»»»\n")
        }
    }
}


import "random" for Random
import "scheduler" for Scheduler
import "timer" for Timer

var Rand = Random.new()

var ForkInUse = List.filled(5, false)

class Fork {
    construct new(name, index) {
        _name = name
        _index = index
    }

    index { _index }

    pickUp(philosopher) {
        System.print("  %(philosopher) picked up %(_name)")
        ForkInUse[index] = true
    }

    putDown(philosopher) {
        System.print("  %(philosopher) put down %(_name)")
        ForkInUse[index] = false
    }
}

class Philosopher {
    construct new(pname, f1, f2) {
        _pname = pname
        _f1 = f1
        _f2 = f2
    }

    delay() { Timer.sleep(Rand.int(300) + 100) }

    eat() {
        (1..5).each { |bite|  // limit to 5 bites say
            while (true) {
                System.print("%(_pname) is hungry")
                if (!ForkInUse[_f1.index] && !ForkInUse[_f2.index]) {
                    _f1.pickUp(_pname)
                    _f2.pickUp(_pname)
                    break
                }
                System.print("%(_pname) is unable to pick up both forks")
                // try again later
                delay()
            }
            System.print("%(_pname) is eating bite %(bite)")
            // allow time to eat
            delay()
            _f2.putDown(_pname)
            _f1.putDown(_pname)
            // allow other philospohers time to pick up forks
            delay()
        }
    }
}

var diningPhilosophers = Fn.new { |names|
    var size = names.count
    var forks = List.filled(size, null)
    for (i in 0...size) forks[i] = Fork.new("Fork %(i + 1)", i)
    var philosophers = []
    var i = 0
    for (n in names) {
        var i1 = i
        var i2 = (i + 1) % size
        if (i2 < i1) {
            i1 = i2
            i2 = i
        }
        var p = Philosopher.new(n, forks[i1], forks[i2])
        philosophers.add(p)
        i = i + 1
    }
    // choose a philosopher at random to start eating
    var r = Rand.int(size)
    // schedule the others to eat later
    for (i in 0...size) if (i != r) Scheduler.add { philosophers[i].eat() }
    philosophers[r].eat()
}

var names = ["Aristotle", "Kant", "Spinoza", "Marx", "Russell"]
diningPhilosophers.call(names)


print numeric? "hello world"
print numeric? "1234"
print numeric? "1234 hello world"
print numeric? "12.34"
print numeric? "!#@$"
print numeric? "-1.23"


list = 0 .14 -5.2 ten 0xf
Loop, Parse, list, %A_Space%
  MsgBox,% IsNumeric(A_LoopField)
Return

IsNumeric(x) {
  If x is number
    Return, 1
  Else Return, 0
}

;Output: 1  1  1  0  1


import "/fmt" for Fmt

// Returns squeezed string, original and new lengths in
// unicode code points (not normalized).
var squeeze = Fn.new { |s, ch|
    var c = s.codePoints.toList
    var le = c.count
    if (le < 2) return [s, le, le]
    for (i in le-2..0) {
        if (c[i] == ch.codePoints[0] && c[i] == c[i+1]) c.removeAt(i)
    }
    var cc = c.reduce("") { |acc, cp| acc + String.fromCodePoint(cp) }
    return [cc, le, cc.count]
}

var strings = [
    "",
    "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
    "..1111111111111111111111111111111111111111111111111111111111111117777888",
    "I never give 'em hell, I just tell the truth, and they think it's hell. ",
    "                                                   ---  Harry S Truman  ",
    "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
    "headmistressship",
    "aardvark",
    "😍😀🙌💃😍😍😍🙌"
]

var chars = [ [" "], ["-"], ["7"], ["."], [" ", "-", "r"], ["e"], ["s"], ["a"], ["😍"] ]

var i = 0
for (s in strings) {
    for (ch in chars[i]) {
        var r = squeeze.call(s, ch)
        System.print("Specified character = '%(ch)'")
        System.print("original : length = %(Fmt.d(2, r[1])), string = «««%(s)»»»")
        System.print("squeezed : length = %(Fmt.d(2, r[2])), string = «««%(r[0])»»»\n")
    }
    i = i + 1
}


var [const] forks=(5).pump(List,Atomic.Bool.fp(False)),  // True==fork in use
    seats=(5).pump(List,'wrap(n){ List(forks[n],forks[(n+1)%5]) });
fcn sitAndEat(name,n){  // assigned seating
   while(1){
      fa,fb:=seats[n].shuffle(); // ambidextrous
      if(fa.setIf(True,False)){  // got the first fork
	 if(fb.setIf(True,False)){  // got the other fork, nom nom time
	    name.println(" is eating");
	    Atomic.sleep((1).random(5));
	    fa.set(False); fb.set(False);  // put forks down
	    return();  // leave the table
	 }
	 else{
	    fa.set(False);  // put fork down, try again in a bit
	    name.println(": Could not get two forks");
	 }
      } else name.println(": Could not get first fork");
      Atomic.sleep((1).random(2));  // sits for a bit
   }
}
fcn philo([(seat,name)]){  // a thread
   while(1){  // eat and think forever
      name.println(" is thinking."); Atomic.sleep((1).random(5));
      sitAndEat(name,seat);
   }
}


$ awk 'function isnum(x){return(x==x+0)} BEGIN{print isnum("hello"),isnum("-42")}'


INPUT "Your string: ", s$

IF REGEX(s$, "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$") THEN
    PRINT "This is a number"
ELSE
    PRINT "Not a number"
ENDIF


string 0;
char C, I, J, Last;

proc Squeeze(Char, S); \Eliminate specified repeated characters from string
char Char, S;
[I:= 0;  J:= 0;  Last:= -1;
loop [if S(I) # Last or Char # Last then
        [C(J):= S(I);
        if S(I) = 0 then quit;
        J:= J+1;
        ];
     Last:= S(I);
     I:= I+1;
     ];
];

int String, K, Char;
[String:= [
    "",
    "^"If I were two-faced, would I be wearing this one?^" --- Abraham Lincoln ",
    "..1111111111111111111111111111111111111111111111111111111111111117777888",
    "I never give 'em hell, I just tell the truth, and they think it's hell. ",
    "                                                    --- Harry S Truman  "];
Char:= [0, ^-, ^1, ^l, ^ , ^-, ^r];
C:= Reserve(79+1);      \space for collapsed string
for K:= 0 to 4+2 do
    [Squeeze(Char(K), String(if K>4 then 4 else K));
    Text(0, "<<<");  Text(0, String(if K>4 then 4 else K));  Text(0, ">>> ");
    IntOut(0, I);  CrLf(0);
    Text(0, "<<<");  Text(0, C);  Text(0, ">>> ");  IntOut(0, J);  CrLf(0);
    ];
]


fcn squeeze(c,str){   // Works with UTF-8
   s,cc,sz,n := Data(Void,str), String(c,c), c.len(), 0; // byte buffer in case of LOTs of deletes
   while(Void != (n=s.find(cc,n))){ str=s.del(n,sz) }  // and searching is faster for big strings
   s.text
}


10 INPUT "Enter a string";S$:GOSUB 1000
20 IF R THEN PRINT "Is num" ELSE PRINT"Not num"
99 END
1000 T1=VAL(S$):T1$=STR$(T1)
1010 R=T1$=S$ OR T1$=" "+S$
1099 RETURN


set /a a=%arg%+0 >nul
if %a% == 0 (
	if not "%arg%"=="0" (
		echo Non Numeric.
	) else (
		echo Numeric.
	)
) else (
	echo Numeric.
)


      REPEAT
        READ N$
        IF FN_isanumber(N$) THEN
          PRINT "'" N$ "' is a number"
        ELSE
          PRINT "'" N$ "' is NOT a number"
        ENDIF
      UNTIL N$ = "end"
      END

      DATA "PI", "0123", "-0123", "12.30", "-12.30", "123!", "0"
      DATA "0.0", ".123", "-.123", "12E3", "12E-3", "12+3", "end"

      DEF FN_isanumber(A$)
      ON ERROR LOCAL = FALSE
      IF EVAL("(" + A$ + ")") <> VAL(A$) THEN = FALSE
      IF VAL(A$) <> 0 THEN = TRUE
      IF LEFT$(A$,1) = "0" THEN = TRUE
      = FALSE


#include <ctype.h>
#include <stdlib.h>
int isNumeric (const char * s)
{
    if (s == NULL || *s == '\0' || isspace(*s))
      return 0;
    char * p;
    strtod (s, &p);
    return *p == '\0';
}


public static bool IsNumeric(string s)
{
    double Result;
    return double.TryParse(s, out Result);  // TryParse routines were added in Framework version 2.0.
}

string value = "123";
if (IsNumeric(value))
{
  // do something
}


#include <sstream> // for istringstream

using namespace std;

bool isNumeric( const char* pszInput, int nNumberBase )
{
	istringstream iss( pszInput );

	if ( nNumberBase == 10 )
	{
		double dTestSink;
		iss >> dTestSink;
	}
	else if ( nNumberBase == 8 || nNumberBase == 16 )
	{
		int nTestSink;
		iss >> ( ( nNumberBase == 8 ) ? oct : hex ) >> nTestSink;
	}
	else
		return false;

	// was any input successfully consumed/converted?
	if ( ! iss )
		return false;

	// was all the input successfully consumed/converted?
	return ( iss.rdbuf()->in_avail() == 0 );
}


(defn numeric? [s]
  (if-let [s (seq s)]
    (let [s (if (= (first s) \-) (next s) s)
          s (drop-while #(Character/isDigit %) s)
          s (if (= (first s) \.) (next s) s)
          s (drop-while #(Character/isDigit %) s)]
      (empty? s))))


        program-id. is-numeric.
        procedure division.
        display function test-numval-f("abc") end-display
        display function test-numval-f("-123.01E+3") end-display
        if function test-numval-f("+123.123") equal zero then
            display "is numeric" end-display
        else
            display "failed numval-f test" end-display
        end-if
        goback.


console.log (isFinite(s) for s in [5, "5", "-5", "5", "5e5", 0]) # all true
console.log (isFinite(s) for s in [NaN, "fred", "###"]) # all false


<cfset TestValue=34>
  TestValue: <cfoutput>#TestValue#</cfoutput>

<cfif isNumeric(TestValue)>
  is Numeric.
<cfelse>
  is NOT Numeric.
</cfif>

<cfset TestValue="NAS">
  TestValue: <cfoutput>#TestValue#</cfoutput>

<cfif isNumeric(TestValue)>
  is Numeric.
<cfelse>
  is NOT Numeric.
</cfif>


(defun numeric-string-p (string)
  (let ((*read-eval* nil))
    (ignore-errors (numberp (read-from-string string)))))


function IsNumericString(const inStr: string): Boolean;
var
  i: extended;
begin
  Result := TryStrToFloat(inStr,i);
end;


func String.IsNumeric() {
    try {
        parse(this) is Integer or Float
    } catch _ {
        false
    }
}

var str = "1234567"
print(str.IsNumeric())


is-numeric s:
	true
	try:
		drop to-num s
	catch value-error:
		not

for v in [ "1" "0" "3.14" "hello" "12e3" "12ef" "-3" ]:
	!.( v is-numeric v )


def isNumeric(specimen :String) {
    try {
        <import:java.lang.makeDouble>.valueOf(specimen)
        return true
    } catch _ {
       return false
    }
}


func is_numeric a$ . r .
  h = number a$
  r = 1 - error
  # because every variable must be used
  h = h
.
for s$ in [ "abc" "21a" "1234" "-13" "7.65" ]
  call is_numeric s$ r
  if r = 1
    print s$ & " is numeric"
  else
    print s$ & " is not numeric"
  .
.


(string->number "albert")
   → #f
(string->number -666)
    → -666
(if (string->number 666) 'YES 'NO)
    → YES


defmodule RC do
  def is_numeric(str) do
    case Float.parse(str) do
      {_num, ""} -> true
      _          -> false
    end
  end
end

["123", "-12.3", "123.", ".05", "-12e5", "+123", " 123", "abc", "123a", "12.3e", "1 2"] |> Enum.filter(&RC.is_numeric/1)


is_numeric(L) ->
    Float = (catch erlang:list_to_float(L)),
    Int = (catch erlang:list_to_integer(L)),
    is_number(Float) orelse is_number(Int).


PROGRAM NUMERIC

PROCEDURE IS_NUMERIC(S$->ANS%)
LOCAL T1,T1$
    T1=VAL(S$)
    T1$=STR$(T1)
    ANS%=(T1$=S$) OR T1$=" "+S$
END PROCEDURE

BEGIN
    PRINT(CHR$(12);)
    INPUT("Enter a string",S$)
    IS_NUMERIC(S$->ANS%)
    IF ANS% THEN PRINT("is num") ELSE PRINT("not num")
END PROGRAM


include get.e

function is_numeric(sequence s)
    sequence val
    val = value(s)
    return val[1]=GET_SUCCESS and atom(val[2])
end function


let is_numeric a = fst (System.Double.TryParse a)


: numeric? ( string -- ? ) string>number >boolean ;


class Main
{
  // function to see if str contains a number of any of built-in types
  static Bool readNum (Str str)
  {
    int := Int.fromStr (str, 10, false)  // use base 10
    if (int != null) return true
    float := Float.fromStr (str, false)
    if (float != null) return true
    decimal := Decimal.fromStr (str, false)
    if (decimal != null) return true

    return false
  }

  public static Void main ()
  {
    echo ("For '2': " + readNum ("2"))
    echo ("For '-2': " + readNum ("-2"))
    echo ("For '2.5': " + readNum ("2.5"))
    echo ("For '2a5': " + readNum ("2a5"))
    echo ("For '-2.1e5': " + readNum ("-2.1e5"))
  }
}


: is-numeric ( addr len -- )
  2dup snumber? ?dup if      \ not standard, but >number is more cumbersome to use
   0< if
     -rot type ."  as integer = " .
   else
     2swap type ."  as double = " <# #s #> type
   then
  else 2dup >float if
    type ."  as float = " f.
  else
    type ."  isn't numeric in base " base @ dec.
  then then ;

s" 1234" is-numeric    \ 1234 as integer = 1234
s" 1234." is-numeric    \ 1234. as double = 1234
s" 1234e" is-numeric    \ 1234e as float = 1234.
s" $1234" is-numeric    \ $1234 as integer = 4660  ( hex literal )
s" %1010" is-numeric    \ %1010 as integer = 10  ( binary literal )
s" beef" is-numeric    \ beef isn't numeric in base 10
hex
s" beef" is-numeric    \ beef as integer = BEEF
s" &1234" is-numeric    \ &1234 as integer = 4D2 ( decimal literal )


FUNCTION is_numeric(string)
  IMPLICIT NONE
  CHARACTER(len=*), INTENT(IN) :: string
  LOGICAL :: is_numeric
  REAL :: x
  INTEGER :: e
  READ(string,*,IOSTAT=e) x
  is_numeric = e == 0
END FUNCTION is_numeric


function isNumeric(const potentialNumeric: string): boolean;
var
	potentialInteger: integer;
	potentialReal: real;
	integerError: integer;
	realError: integer;
begin
	integerError := 0;
	realError := 0;

	// system.val attempts to convert numerical value representations.
	// It accepts all notations as they are accepted by the language,
	// as well as the '0x' (or '0X') prefix for hexadecimal values.
	val(potentialNumeric, potentialInteger, integerError);
	val(potentialNumeric, potentialReal, realError);

	isNumeric := (integerError = 0) or (realError = 0);
end;


' FB 1.05.0 Win64

Dim Shared symbols(0 To 15) As UByte
For i As Integer = 48 to 57
  symbols(i - 48) = i
Next
For i As Integer = 97 to 102
  symbols(i - 87) = i
Next

Const plus  As UByte = 43
Const minus As Ubyte = 45
Const dot   As UByte = 46

Function isNumeric(s As Const String, base_ As Integer = 10) As Boolean
  If s = "" OrElse s = "."  OrElse s = "+" OrElse s = "-" Then Return False
  Err = 0

  If base_ < 2 OrElse base_ > 16 Then
    Err = 1000
    Return False
  End If

  Dim t As String = LCase(s)

  If (t[0] = plus) OrElse (t[0] = minus) Then
     t = Mid(t, 2)
  End If

  If Left(t, 2) = "&h" Then
    If base_ <> 16 Then Return False
    t = Mid(t, 3)
  End if

  If Left(t, 2) = "&o" Then
    If base_ <> 8 Then Return False
    t = Mid(t, 3)
  End if

  If Left(t, 2) = "&b" Then
    If base_ <> 2 Then Return False
    t = Mid(t, 3)
  End if

  If Len(t) = 0 Then Return False
  Dim As Boolean isValid, hasDot = false

  For i As Integer = 0 To Len(t) - 1
    isValid = False

    For j As Integer = 0 To base_ - 1
      If t[i] = symbols(j) Then
        isValid = True
        Exit For
      End If
      If t[i] = dot Then
        If CInt(Not hasDot) AndAlso (base_ = 10) Then
          hasDot = True
          IsValid = True
          Exit For
        End If
        Return False ' either more than one dot or not base 10
      End If
    Next j

    If Not isValid Then Return False
  Next i

  Return True
End Function

Dim s As String
s = "1234.056789"
Print s, " (base 10) => "; isNumeric(s)
s = "1234.56"
Print s, " (base 7)  => "; isNumeric(s, 7)
s = "021101"
Print s, " (base 2)  => "; isNumeric(s, 2)
s = "Dog"
Print s, " (base 16) => "; isNumeric(s, 16)
s = "Bad125"
Print s, " (base 16) => "; isNumeric(s, 16)
s = "-0177"
Print s, " (base 8)  => "; isNumeric(s, 8)
s = "+123abcd.ef"
Print s, " (base 16) => "; isNumeric(s, 8)
s = "54321"
Print s, " (base 6)  => "; isNumeric(s, 6)
s = "123xyz"
Print s, " (base 10) => "; isNumeric(s)
s = "xyz"
Print s, " (base 10) => "; isNumeric(s)
Print
Print "Press any key to quit"
Sleep


Public Sub Form_Open()
Dim sAnswer, sString As String

sString = Trim(InputBox("Enter as string", "String or Numeric"))

If IsNumber(sString) Then sAnswer = "'" & sString & "' is numeric" Else sAnswer = "'" & sString & "' is a string"
Print sAnswer

End


package main

import (
    "fmt"
    "strconv"
)

func isNumeric(s string) bool {
    _, err := strconv.ParseFloat(s, 64)
    return err == nil
}

func main() {
    fmt.Println("Are these strings numeric?")
    strings := []string{"1", "3.14", "-100", "1e2", "NaN", "rose"}
    for _, s := range strings {
        fmt.Printf("  %4s -> %t\n", s, isNumeric(s))
    }
}


def isNumeric = {
    def formatter = java.text.NumberFormat.instance
    def pos = [0] as java.text.ParsePosition
    formatter.parse(it, pos)

    // if parse position index has moved to end of string
    // them the whole string was numeric
    pos.index == it.size()
}


isInteger s = case reads s :: [(Integer, String)] of
  [(_, "")] -> True
  _         -> False

isDouble s = case reads s :: [(Double, String)] of
  [(_, "")] -> True
  _         -> False

isNumeric :: String -> Bool
isNumeric s = isInteger s || isDouble s


static function isNumeric(n:String):Bool
{
	if (Std.parseInt(n) != null) //Std.parseInt converts a string to an int
        {
		return true; //as long as it results in an integer, the function will return true
	}
        else
        {
		return false;
	}
}


                              !    = bin + 2*int + 4*flt + 8*oct +16*hex + 32*sci
   isNumeric("1001")          ! 27 =  1       1       0       1       1        0
   isNumeric("123")           ! 26 =  0       1       0       1       1        0
   isNumeric("1E78")          ! 48 =  0       0       0       0       1        1
   isNumeric("-0.123")        !  4 =  0       0       1       0       0        1
   isNumeric("-123.456e-78")  ! 32 =  0       0       0       0       0        1
   isNumeric(" 123")          !  0: leading blank
   isNumeric("-123.456f-78")  !  0: illegal character f

FUNCTION isNumeric(string)    ! true ( > 0 ), no leading/trailing blanks
   CHARACTER string
   b = INDEX(string, "[01]+", 128, Lbin)                ! Lbin returns length found
   i = INDEX(string, "-?\d+", 128, Lint)                ! regular expression: 128
   f = INDEX(string, "-?\d+\.\d*", 128, Lflt)
   o = INDEX(string, "[0-7]+",    128, Loct)
   h = INDEX(string, "[0-9A-F]+", 128, Lhex)            ! case sensitive: 1+128
   s = INDEX(string, "-?\d+\.*\d*E[+-]*\d*", 128, Lsci)
   IF(anywhere) THEN     ! 0 (false) by default
     isNumeric = ( b > 0 ) + 2*( i > 0 ) + 4*( f > 0 ) + 8*( o > 0 ) + 16*( h > 0 ) + 32*( s > 0 )
   ELSEIF(boolean) THEN  ! 0 (false) by default
     isNumeric = ( b + i + f + o + h + s ) > 0 ! this would return 0 or 1
   ELSE
     L = LEN(string)
     isNumeric = (Lbin==L) + 2*(Lint==L) + 4*(Lflt==L) + 8*(Loct==L) + 16*(Lhex==L) + 32*(Lsci==L)
   ENDIF
 END


concept numeric(n) {
	number(n)
	errors {
		print(n, "  is not numeric!")
		return
	}
	print(n, "  is numeric :)")
}

software {
	numeric("1200")
	numeric("3.14")
	numeric("3/4")
	numeric("abcdefg")
	numeric("1234test")
}


write(image(x), if numeric(x) then " is numeric." else " is not numeric")


function isnumeric,input
  on_ioerror, false
  test = double(input)
  return, 1
  false: return, 0
end


isNumeric=: _ ~: _ ". ]
isNumericScalar=: 1 -: isNumeric
TXT=: ,&' a scalar numeric value.' &.> ' is not';' represents'
sayIsNumericScalar=: , TXT {::~ isNumericScalar


public boolean isNumeric(String input) {
  try {
    Integer.parseInt(input);
    return true;
  }
  catch (NumberFormatException e) {
    // s is not numeric
    return false;
  }
}


function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
var value = "123.45e7"; // Assign string literal to value
if (isNumeric(value)) {
  // value is a number
}
//Or, in web browser in address field:
//  javascript:function isNumeric(n) {return !isNaN(parseFloat(n)) && isFinite(n);}; value="123.45e4"; if(isNumeric(value)) {alert('numeric')} else {alert('non-numeric')}


// version 1.1

fun isNumeric(input: String): Boolean =
    try {
        input.toDouble()
        true
    } catch(e: NumberFormatException) {
        false
    }

fun main(args: Array<String>) {
    val inputs = arrayOf("152", "-3.1415926", "Foo123", "-0", "456bar", "1.0E10")
    for (input in inputs) println("$input is ${if (isNumeric(input)) "numeric" else "not numeric"}")
}


local(str='12345')
string_isNumeric(#str) // true


DATA "PI", "0123", "-0123", "12.30", "-12.30", "123!", "0"
DATA "0.0", ".123", "-.123", "12E3", "12E-3", "12+3", "end"

while n$ <> "end"
    read n$
    print n$, IsNumber(n$)
wend
end

function IsNumber(string$)
    on error goto [NotNumber]
    string$ = trim$(string$)
    'check for float overflow
    n = val(string$)

    'assume it is number and try to prove wrong
    IsNumber = 1
    for i = 1 to len(string$)
        select case mid$(string$, i, 1)
            case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
                HasNumeric = 1 'to check if there are any digits
            case "e", "E"
                '"e" must not occur more than once
                'must not occur before digits

                if HasE > 0 or HasNumeric = 0 then
                    IsNumber = 0
                    exit for
                end if
                HasE = i 'store position of "e"
                HasNumeric = 0 'needs numbers after "e"
            case "-", "+"
                'must be either first character or immediately after "e"
                '(HasE = 0 if no occurrences yet)
                if HasE <> i-1 then
                    IsNumber = 0
                    exit for
                end if
            case "."
                'must not have previous points and must not come after "e"
                if HasE <> 0 or HasPoint <> 0 then
                    IsNumber = 0
                    exit for
                end if
                HasPoint = 1
            case else
                'no other characters allowed
                IsNumber = 0
                exit for
        end select
    next i
    'must have digits
    if HasNumeric = 0 then IsNumber = 0
    [NotNumber]
end function


"123457".is_integer.println;
// write TRUE on stdin


if tonumber(a) ~= nil then
   --it's a number
end;


\\ version 2
Module Checkit {
      function global isNumber(a$, de$=".") {
            =false=true  ' return boolean
            if de$="" then de$=str$(.1,".")  ' get current decimal point character
            a$=trim$(ucase$(a$))
            m=len(a$)
            if m=0 then exit
            c$=filter$(a$,"0123456789")
            if c$ = "" then {
                  =true
            } else.if m>1 then {
                  \ may have -+ and ,
                  if m=2 then {
                        if not c$~"[-+\"+de$+"]" then break
                  } else {
                        if left$(c$,1 ) ~"[+-]" then c$=mid$(c$, 2)
                        if not (c$=de$ or c$=de$+"E" or c$ ~ de$+"E[+-]") then break
                        if c$ ~ de$+"E[+-]" then if not (instr(a$,"E+")>0 or instr(a$,"E-")>0) then break
                  }
                 if de$<>"." then  a$=replace$(de$, ".", a$, 1,1)
                 try {inline "a="+a$+"=="+a$}
                 if valid(a) then =a = true=true  ' return boolean
             }
      }
      Print isNumber("+1"), isnumber("-1"), isNumber("1+")=false, isnumber("1-")=false
      Print isNumber(",1",","), isnumber("1,",","), isNumber(",0",","), isnumber("0,", ",")
      Print isNumber(".1"), isnumber("1."), isNumber(".0"), isnumber("0.")
      Print isNumber("+.1"), isnumber("-1."), isNumber(".12e+232"), isnumber("0.122e10")
      Print isNumber("+.1a")=false, isnumber("asasa1212")=false, isNumber("1.2e43+23")=false, isnumber("0.122e10")
      Print isNumber("1221.211.1221")=false, isnumber("1221e1212")=false, isNumber("1.2e4323")=false, isnumber("-.122e-10")
}
Checkit


isNumeric := proc(s)
	try
		if type(parse(s), numeric) then
			printf("The string is numeric."):
		else
			printf("The string is not numeric."):
		end if:
	catch:
		printf("The string is not numeric."):
	end try:
end proc:


  function r = isnum(a)
    r = ~isnan(str2double(a))
  end

% tests
disp(isnum(123)) % 1
disp(isnum("123")) % 1
disp(isnum("foo123")) % 0
disp(isnum("123bar")) % 0
disp(isnum("3.1415")) % 1


fn isNumeric str =
(
    try
    (
        (str as integer) != undefined
    )
    catch(false)
)

isNumeric "123"


(
  dup (((int integer?) (pop false)) try) dip
  ((float float?) (pop false)) try or
) :numeric?


isNumeric = function(s)
    return s == "0" or s == "-0" or val(s) != 0
end function

print isNumeric("0")
print isNumeric("42")
print isNumeric("-3.14157")
print isNumeric("[email protected]*#!")
print isNumeric("spam")


# $a0 char val
# $a1 address pointer
# $a2 PERIOD_HIT_FLAG
# $a3 HAS_DIGITS_FLAG

.data
			### CHANGE THIS STRING TO TEST DIFFERENT ONES... ###
	string: .asciiz "-.1236"
	s_false: .asciiz "False"
	s_true: .asciiz "True"
.text
main:
	set_up: #test for 0th char == 45 or 46 or 48...57
		la $a1,string
		lb $a0,($a1)
		beq $a0,45,loop # == '-'
		beq $a0,46,loop # == '.'
		blt $a0,48,exit_false # isn't below the ascii range for chars '0'...'9'
		bgt $a0,57,exit_false # isn't above the ascii range for chars '0'...'9'
	loop:
		addi $a1,$a1,1
		lb $a0,($a1)
		beqz $a0,exit_true # test for \0 null char
		beq $a0,46,period_test #test for a duplicate period
		blt $a0,48,exit_false  #test for
		bgt $a0,57,exit_false
		la $a3,1 #set the HAS_DIGITS flag. This line is only reached because the
			 #    tests for period and - both jump back to start.
		j loop

exit_true:
	beqz $a3,exit_false
	la $a0,s_true
	la $v0,4
	syscall

	li $v0,10
	syscall

exit_false:
	la $a0,s_false
	la $v0,4
	syscall

	li $v0,10
	syscall

period_test:
	beq $a2,1,exit_false
	li $a2,1
	j loop


import java.text.NumberFormat
import java.text.ParsePosition
import java.util.Scanner

# this first example relies on catching an exception,
# which is bad style and poorly performing in Java
def is_numeric?(s:string)
    begin
        Double.parseDouble(s)
        return true
    rescue
        return false
    end
end

puts '123   is numeric' if is_numeric?('123')
puts '-123  is numeric' if is_numeric?('-123')
puts '123.1 is numeric' if is_numeric?('123.1')

puts 'nil   is not numeric' unless is_numeric?(nil)
puts "''    is not numeric" unless is_numeric?('')
puts 'abc   is not numeric' unless is_numeric?('abc')
puts '123-  is not numeric' unless is_numeric?('123-')
puts '1.2.3 is not numeric' unless is_numeric?('1.2.3')

# check every element of the string
def is_numeric2?(s: string)
    if (s == nil || s.isEmpty())
        return false
    end
    if (!s.startsWith('-'))
        if s.contains('-')
            return false
        end
    end

    0.upto(s.length()-1) do |x|
        c = s.charAt(x)
        if ((x == 0) && (c == '-'.charAt(0)))
            # negative number
        elsif (c == '.'.charAt(0))
            if (s.indexOf('.', x) > -1)
                return false # more than one period
            end
        elsif (!Character.isDigit(c))
            return false
        end
    end
    true
end

puts '123   is numeric' if is_numeric2?('123')
puts '-123  is numeric' if is_numeric2?('-123')
puts '123.1 is numeric' if is_numeric2?('123.1')

puts 'nil   is not numeric' unless is_numeric2?(nil)
puts "''    is not numeric" unless is_numeric2?('')
puts 'abc   is not numeric' unless is_numeric2?('abc')
puts '123-  is not numeric' unless is_numeric2?('123-')
puts '1.2.3 is not numeric' unless is_numeric2?('1.2.3')

# use a regular  expression
def is_numeric3?(s:string)
  s == nil || s.matches("[-+]?\\d+(\\.\\d+)?")
end

puts '123   is numeric' if is_numeric3?('123')
puts '-123  is numeric' if is_numeric3?('-123')
puts '123.1 is numeric' if is_numeric3?('123.1')

puts 'nil   is not numeric' unless is_numeric3?(nil)
puts "''    is not numeric" unless is_numeric3?('')
puts 'abc   is not numeric' unless is_numeric3?('abc')
puts '123-  is not numeric' unless is_numeric3?('123-')
puts '1.2.3 is not numeric' unless is_numeric3?('1.2.3')

#  use the positional parser in the java.text.NumberFormat object
# (a more robust solution). If, after parsing, the parse position is at
# the end of the string, we can deduce that the entire string was a
# valid number.
def is_numeric4?(s:string)
    return false if s == nil
    formatter = NumberFormat.getInstance()
    pos = ParsePosition.new(0)
    formatter.parse(s, pos)
    s.length() == pos.getIndex()
end

puts '123   is numeric' if is_numeric4?('123')
puts '-123  is numeric' if is_numeric4?('-123')
puts '123.1 is numeric' if is_numeric4?('123.1')

puts 'nil   is not numeric' unless is_numeric4?(nil)
puts "''    is not numeric" unless is_numeric4?('')
puts 'abc   is not numeric' unless is_numeric4?('abc')
puts '123-  is not numeric' unless is_numeric4?('123-')
puts '1.2.3 is not numeric' unless is_numeric4?('1.2.3')

# use the java.util.Scanner object. Very useful if you have to
# scan multiple entries. Scanner also has similar methods for longs,
# shorts, bytes, doubles, floats, BigIntegers, and BigDecimals as well
# as methods for integral types where you may input a base/radix other than
# 10 (10 is the default, which can be changed using the useRadix method).
def is_numeric5?(s:string)
    return false if s == nil
    Scanner sc = Scanner.new(s)
    sc.hasNextDouble()
end

puts '123   is numeric' if is_numeric5?('123')
puts '-123  is numeric' if is_numeric5?('-123')
puts '123.1 is numeric' if is_numeric5?('123.1')

puts 'nil   is not numeric' unless is_numeric5?(nil)
puts "''    is not numeric" unless is_numeric5?('')
puts 'abc   is not numeric' unless is_numeric5?('abc')
puts '123-  is not numeric' unless is_numeric5?('123-')
puts '1.2.3 is not numeric' unless is_numeric5?('1.2.3')


var %value = 3
if (%value isnum) {
  echo -s %value is numeric.
}


MODULE Numeric EXPORTS Main;

IMPORT IO, Fmt, Text;

PROCEDURE isNumeric(s: TEXT): BOOLEAN =
  BEGIN
    FOR i := 0 TO Text.Length(s) DO
      WITH char = Text.GetChar(s, i) DO
        IF i = 0 AND char = '-' THEN
          EXIT;
        END;
        IF char >= '0' AND char <= '9' THEN
          EXIT;
        END;
        RETURN FALSE;
      END;
    END;
    RETURN TRUE;
  END isNumeric;

BEGIN
  IO.Put("isNumeric(152) = " & Fmt.Bool(isNumeric("152")) & "\n");
  IO.Put("isNumeric(-3.1415926) = " & Fmt.Bool(isNumeric("-3.1415926")) & "\n");
  IO.Put("isNumeric(Foo123) = " & Fmt.Bool(isNumeric("Foo123")) & "\n");
END Numeric.


USER>WRITE +"1"
1
USER>WRITE +"1A"
1
USER>WRITE +"A1"
0
USER>WRITE +"1E"
1
USER>WRITE +"1E2"
100
USER>WRITE +"1EA24"
1
USER>WRITE +"1E3A"
1000
USER>WRITE +"1E-3"
.001


def isNum(str)
    try
        double(str)
        return true
    catch
        return false
    end
end


using System;
using System.Console;

module IsNumeric
{
    IsNumeric( input : string) : bool
    {
        mutable meh = 0.0;  // I don't want it, not going to use it, why force me to declare it?
        double.TryParse(input, out meh)
    }

    Main() : void
    {
        def num = "-1.2345E6";
        def not = "abc45";
        WriteLine($"$num is numeric: $(IsNumeric(num))");
        WriteLine($"$not is numeric: $(IsNumeric(not))");
    }
}


/* NetRexx */
options replace format comments java crossref symbols nobinary

numeric digits 20

loop n_ over getTestData()
  -- could have used n_.datatype('N') directly here...
  if isNumeric(n_) then msg = 'numeric'
                   else msg = 'not numeric'
  say ('"'n_'"').right(25)':' msg
  end n_

return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Pointless in NetRexx; the DATATYPE built-in-function is more powerful!
method isNumeric(testString) public static returns boolean
  return testString.datatype('N')

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getTestData() private static returns Rexx[]

  -- Coercing numbers into the Rexx type has the effect of converting them to strings.
  -- NetRexx will still perform arithmetic on Rexx strings if those strings represent numbers.
  -- Notice that whitespace between the sign and the number are ignored even when inside a string constant
  testData = [ Rexx -
    ' one and a half',   1,   1.5,    1.5e+27, '   1 ', '  1.5 ', '  1.5e+27 ', -
    '-one and a half', - 1, - 1.5,  - 1.5e-27, ' - 1 ', '- 1.5 ', '- 1.5e-27 ', -
    '+one and a half', + 1, + 1.5,  + 1.5e+27, ' + 1 ', '+ 1.5 ', '+ 1.5e+27 ', -
    'Math Constants', -
     Math.PI,  Math.E, -
    -Math.PI, -Math.E, -
    +Math.PI, +Math.E, -
    'Numeric Constants', -
    Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY -
    ]
  return testData


import strutils

proc isNumeric(s: string): bool =
  try:
    discard s.parseFloat()
    result = true
  except ValueError:
    result = false

const Strings = ["1", "3.14", "-100", "1e2", "Inf", "rose"]

for s in Strings:
  echo s, " is ", if s.isNumeric(): "" else: "not ", "numeric"


class Numeric {
  function : Main(args : String[]) ~ Nil {
    if(args->Size() = 1) {
      IsNumeric(args[0])->PrintLine();
    };
  }

  function : IsNumeric(str : String) ~ Bool {
    return str->IsFloat();
  }
}


if( [[NSScanner scannerWithString:@"-123.4e5"] scanFloat:NULL] )
	NSLog( @"\"-123.4e5\" is numeric" );
else
	NSLog( @"\"-123.4e5\" is not numeric" );
if( [[NSScanner scannerWithString:@"Not a number"] scanFloat:NULL] )
	NSLog( @"\"Not a number\" is numeric" );
else
	NSLog( @"\"Not a number\" is not numeric" );
// prints: "-123.4e5" is numeric
// prints: "Not a number" is not numeric


let is_int s =
  try ignore (int_of_string s); true
  with _ -> false

let is_float s =
  try ignore (float_of_string s); true
  with _ -> false

let is_numeric s = is_int s || is_float s


function r = isnum(a)
  if ( isnumeric(a) )
    r = 1;
  else
    r = ~isnan(str2double(a));
  endif
endfunction

% tests
disp(isnum(123))      % 1
disp(isnum("123"))    % 1
disp(isnum("foo123")) % 0
disp(isnum("123bar")) % 0
disp(isnum("3.1415")) % 1


fun {IsNumeric S}
   {String.isInt S} orelse {String.isFloat S}
end


isNumeric(s)={
  my(t=type(eval(s)));
  t == "t_INT" || t == "T_REAL"
};


Built-In Function
Syntax

IsNumber(Value)
Description

Use the IsNumber function to determine if Value contains a valid numeric value. Numeric characters include sign indicators and comma and period decimal points.
To determine if a value is a number and if it's in the user's local format, use the IsUserNumber function.

Parameters

Value
Specify a string you want to search to determine if it is a valid number.

Returns
A Boolean value: True if Value contains a valid numeric value, False otherwise.

Example

&Value = Get Field().Value;
If IsNumber(&Value) Then
   /* do numeric processing */
Else
   /* do non-numeric processing */
End-if;


use Scalar::Util qw(looks_like_number);
print looks_like_number($str) ? "numeric" : "not numeric\n";


<?php
$string = '123';
if(is_numeric(trim($string))) {
}
?>


int(0..1) is_number(string s)
{
    array test = array_sscanf(s, "%s%f%s");
    if (sizeof(test) == 3 && test[1] && !sizeof(test[0]) && !sizeof(test[2]) )
        return true;
    else
        return false;
}

string num = "-1.234"
is_number(num);
-> true


is_numeric: procedure (text) returns (bit (1));
   declare text character (*);
   declare x float;

   on conversion go to done;

   get string(text) edit (x) (E(length(text),0));
   return ('1'b);

done:
   return ('0'b);
end is_numeric;


FUNCTION IsNumeric( VALUE IN VARCHAR2 )
RETURN BOOLEAN
IS
  help NUMBER;
BEGIN
  help := TO_NUMBER( VALUE );
  RETURN( TRUE );
EXCEPTION
  WHEN OTHERS THEN
    RETURN( FALSE );
END;


To run:
Start up.
Show whether "cat" is numeric.
Show whether "3" is numeric.
Show whether "+3" is numeric.
Show whether "-123" is numeric.
Show whether "123,456" is numeric.
Show whether "11/5" is numeric.
Show whether "-26-1/3" is numeric.
Show whether "+26-1/3" is numeric.
Show whether "1/0" is numeric. \in Plain English, 1/0 is 0. Don't tell the mathematicians!
Show whether "3.14159" is numeric. \floating point is not implemented in Plain English.
Wait for the escape key.
Shut down.

To show whether a string is numeric:
Write the string then " -> " on the console without advancing.
If the string is any numeric literal, write "yes" on the console; exit.
Write "no" on the console.


function isNumeric ($x) {
    try {
        0 + $x | Out-Null
        return $true
    } catch {
        return $false
    }
}


numeric_string(String) :-
    atom_string(Atom, String),
    atom_number(Atom, _).


Procedure IsNumeric(InString.s, DecimalCharacter.c = '.')
  #NotNumeric = #False
  #IsNumeric = #True

  InString = Trim(InString)
  Protected IsDecimal, CaughtDecimal, CaughtE
  Protected IsSignPresent, IsSignAllowed = #True, CountNumeric
  Protected *CurrentChar.Character = @InString

  While *CurrentChar\c
    Select *CurrentChar\c
      Case '0' To '9'
        CountNumeric + 1
        IsSignAllowed = #False
      Case DecimalCharacter
        If CaughtDecimal Or CaughtE Or CountNumeric = 0
          ProcedureReturn #NotNumeric
        EndIf

        CountNumeric = 0
        CaughtDecimal = #True
        IsDecimal = #True
      Case  '-', '+'
        If IsSignPresent Or Not IsSignAllowed: ProcedureReturn #NotNumeric: EndIf
        IsSignPresent = #True
      Case 'E', 'e'
        If CaughtE Or CountNumeric = 0
          ProcedureReturn #NotNumeric
        EndIf

        CaughtE = #True
        CountNumeric = 0
        CaughtDecimal = #False
        IsSignPresent = #False
        IsSignAllowed = #True
      Default
        ProcedureReturn #NotNumeric
    EndSelect
    *CurrentChar + SizeOf(Character)
  Wend

  If CountNumeric = 0: ProcedureReturn #NotNumeric: EndIf
  ProcedureReturn #IsNumeric
EndProcedure

If OpenConsole()
  PrintN("'+3183.31151E+321' = " + Str(IsNumeric("+3183.31151E+321")))
  PrintN("'-123456789' = " + Str(IsNumeric("-123456789")))
  PrintN("'123.45.6789+' = " + Str(IsNumeric("123.45.6789+")))
  PrintN("'-e' = " + Str(IsNumeric("-e")))
  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf


def is_numeric(s):
    try:
        float(s)
        return True
    except (ValueError, TypeError):
        return False

is_numeric('123.0')


  [ char . over find
    tuck over found iff
      [ swap pluck drop ]
    else nip ]                  is -point  ( $ --> $ )

  [ -point $->n nip ]           is numeric ( $ --> b )

  [ dup echo$ say " is"
    numeric not if say " not"
    say " a valid number." cr ] is task    ( $ -->   )

  $ "152"        task
  $ "-3.1415926" task
  $ "Foo123"     task


> strings <- c("152", "-3.1415926", "Foo123")
> suppressWarnings(!is.na(as.numeric(strings)))
[1]  TRUE  TRUE FALSE


(define (string-numeric? s) (number? (string->number s)))


sub is-number-w-ws( Str $term --> Bool ) { # treat Falsey strings as numeric
    $term.Numeric !~~ Failure;
}

sub is-number-wo-ws( Str $term --> Bool ) { # treat Falsey strings as non-numeric
    ?($term ~~ / \S /) && $term.Numeric !~~ Failure;
}

say "               Coerce     Don't coerce";
say '    String   whitespace    whitespace';
printf "%10s  %8s  %11s\n",
"<$_>", .&is-number-w-ws, .&is-number-wo-ws for
(|<1 1.2 1.2.3 -6 1/2 12e B17 1.3e+12 1.3e12 -2.6e-3 zero 0x 0xA10 0b1001 0o16
0o18 2+5i True False Inf NaN 0x10.50 0b102 0o_5_3 ௫௯>, '  12  ', '1 1 1', '', ' ' ).map: *.Str;


isnumeric
$Typecheck on

Defint FALSE, TRUE

FALSE = 0
TRUE = NOT FALSE

Function isNumeric(s as string, optchar as string) as integer
    If len(s) = 0 then
        Result = FALSE
        Exit Function
    End If
    if instr(s,"+") > 1 then
        Result = FALSE
        exit function
    end if
    if instr(s,"-") > 1 then
        Result = FALSE
        exit function
    end if
    Defint i, ndex = 0
    For i = 1 to len(s)
        select case asc(mid$(s,i,1))
        case 43   '+
        case 45   '-
        case 46 '.
            if ndex = 1 then
                Result = FALSE
                Exit function
            end if
            ndex = 1
        case 48 to 57  '0 to 9
        case else
            if instr(optchar,(mid$(s,i,1))) = 0 then
                Result = FALSE
                exit function
            end if
        end select
    next
    Result = TRUE
End Function

'============================================================
'Begin
'============================================================

showmessage (str$(isNumeric("-152.34","")))
end


rebol [
	Title: "Is Numeric?"
	URL: http://rosettacode.org/wiki/IsNumeric
]

; Built-in.

numeric?: func [x][not error? try [to-decimal x]]

; Parse dialect for numbers.

sign:   [0 1 "-"]
digit:  charset "0123456789"
int:    [some digit]
float:  [int "." int]
number: [
	sign float ["e" | "E"] sign int |
	sign int ["e" | "E"] sign int |
	sign float |
	sign int
]

pnumeric?: func [x][parse x number]

; Test cases.

cases: parse {
   10 -99
   10.43 -12.04
   1e99 1.0e10 -10e3 -9.12e7 2e-4 -3.4E-5
   3phase  Garkenhammer  e  n3v3r  phase3
} none
foreach x cases [print [x  numeric? x  pnumeric? x]]


'123 a:from-string TRUE [ swap c:digit? and ] a:reduce


/*REXX program determines if a string is numeric,  using REXX's rules for numbers.      */
yyy=' -123.78'                                   /*or some such.                        */

                                                 /*strings below are all numeric (REXX).*/
zzz= ' -123.78 '
zzz= '-123.78'
zzz= '2'
zzz= "2"
zzz= 2
zzz= '000000000004'
zzz= '+5'
zzz=  +5
zzz= ' +6 '
zzz= ' + 7 '
zzz= ' - 8 '
zzz= ' - .9'
zzz= '- 19.'
zzz= '.7'
zzz=  .7
zzz= '2e3'
zzz= 47e567
zzz= '2e-3'
zzz= '1.2e1'
zzz= ' .2E6'
zzz= ' 2.e5 '
zzz= '       +1.2E0002 '
zzz= '       +1.2e+002 '
zzz= ' +0000001.200e+002 '
zzz= ' - 000001.200e+002 '
zzz= ' - 000008.201e-00000000000000002 '

                     /*Note:  some REXX interpreters allow use of tab chars as blanks.  */

                     /*all statements below are equivalent.*/

if \datatype(yyy, 'n')        then say 'oops, not numeric:'  yyy
if \datatype(yyy, 'N')        then say 'oops, not numeric:'  yyy
if ¬datatype(yyy, 'N')        then say 'oops, not numeric:'  yyy
if ¬datatype(yyy, 'numeric')  then say 'oops, not numeric:'  yyy
if ¬datatype(yyy, 'nimrod.')  then say 'oops, not numeric:'  yyy
if  datatype(yyy) \== 'NUM'   then say 'oops, not numeric:'  yyy
if  datatype(yyy) /== 'NUM'   then say 'oops, not numeric:'  yyy
if  datatype(yyy) ¬== 'NUM'   then say 'oops, not numeric:'  yyy
if  datatype(yyy) ¬=  'NUM'   then say 'oops, not numeric:'  yyy

                /*note:  REXX only looks at the first char for DATATYPE's  2nd argument.*/

                /*note:  some REXX interpreters don't support the  ¬  (not)  character. */


see isdigit("0123456789") + nl +        # print 1
    isdigit("0123a")                    # print 0


def is_numeric?(s)
  begin
    Float(s)
  rescue
    false # not numeric
  else
    true # numeric
  end
end


print isNumeric("123")
print isNumeric("1ab")

' ------------------------
' Numeric Check
' 0 = bad
' 1 = good
' ------------------------
FUNCTION isNumeric(f$)
isNumeric = 1
f$	= trim$(f$)
if left$(f$,1) = "-" or left$(f$,1) = "+" then f$ = mid$(f$,2)
for i = 1 to len(f$)
        d$ = mid$(f$,i,1)
	if d$ = "," then goto [nxtDigit]
	if d$ = "." then
                if dot$ = "." then isNumeric = 0
		dot$	= "."
		goto [nxtDigit]
	end if
       if (d$ < "0") or (d$ > "9") then isNumeric = 0
[nxtDigit]
next i
END FUNCTION


// This function is not limited to just numeric types but rather anything that implements the FromStr trait.
fn parsable<T: FromStr>(s: &str) -> bool {
    s.parse::<T>().is_ok()
}


import scala.util.control.Exception.allCatch

def isNumber(s: String): Boolean = (allCatch opt s.toDouble).isDefined


(define (numeric? s) (string->number s))


$ include "seed7_05.s7i";
  include "scanstri.s7i";

const func boolean: isNumeric (in var string: stri) is func
  result
    var boolean: isNumeric is FALSE;
  local
    var string: numberStri is "";
  begin
    numberStri := getNumber(stri);
    isNumeric := stri = "";
  end func;


say "0.1E-5".looks_like_number;       #=> true


BEGIN

    BOOLEAN PROCEDURE ISNUMERIC(W); TEXT W;
    BEGIN
        BOOLEAN PROCEDURE MORE;
            MORE := W.MORE;
        CHARACTER PROCEDURE NEXT;
            NEXT := IF MORE THEN W.GETCHAR ELSE CHAR(0);
        CHARACTER PROCEDURE LAST;
            LAST := IF W.LENGTH = 0
                    THEN CHAR(0)
                    ELSE W.SUB(W.LENGTH,1).GETCHAR;
        CHARACTER CH;
        W.SETPOS(1);
        IF MORE THEN
        BEGIN
            CH := NEXT;
            IF CH = '-' OR CH = '+' THEN CH := NEXT;
            WHILE DIGIT(CH) DO CH := NEXT;
            IF CH = '.' THEN
            BEGIN
                CH := NEXT;
                IF NOT DIGIT(CH) THEN GOTO L;
                WHILE DIGIT(CH) DO CH := NEXT;
            END;
            IF CH = '&' THEN
            BEGIN
                CH := NEXT;
                IF CH = '-' OR CH = '+' THEN CH := NEXT;
                WHILE DIGIT(CH) DO CH := NEXT;
            END;
        END;
    L:  ISNUMERIC := (W.LENGTH > 0) AND THEN (NOT MORE) AND THEN DIGIT(LAST);
    END;

    REAL X;
    TEXT T;
    FOR X := 0, -3.1415, 2.768&+31, 5&10, .5, 5.&10 DO
    BEGIN
        OUTREAL(X, 10, 20);
        OUTIMAGE;
    END;

    OUTIMAGE;

    FOR T :- "0", "-3.1415", "2.768&+31", ".5", "5&22" DO
    BEGIN
        OUTTEXT(IF ISNUMERIC(T) THEN "    NUMERIC " ELSE "NOT NUMERIC ");
        OUTCHAR('"');
        OUTTEXT(T);
        OUTCHAR('"');
        IF T = "0" THEN OUTCHAR(CHAR(9)); OUTCHAR(CHAR(9));
        COMMENT PROBE ;
        X := T.GETREAL;
        OUTREAL(X, 10, 20);
        OUTIMAGE;
    END;

    OUTIMAGE;

    X := 5.&10;
   !X := 5&;
   !X := 5.;
    X := .5;
    FOR T :- "", "5.", "5&", "5&+", "5.&", "5.&-", "5.&10" DO
    BEGIN
        OUTTEXT(IF ISNUMERIC(T) THEN "    NUMERIC " ELSE "NOT NUMERIC ");
        OUTCHAR('"');
        OUTTEXT(T);
        OUTCHAR('"');
        OUTIMAGE;
    END;

END


String extend [
  realIsNumeric [
     (self first = $+) |
     (self first = $-)
        ifTrue: [
           ^ (self allButFirst) isNumeric
        ]
        ifFalse: [
           ^ self isNumeric
        ]
  ]
]

{ '1234'.            "true"
  '3.14'. '+3.8111'. "true"
  '+45'.             "true"
  '-3.78'.           "true"
  '-3.78.23'. "false"
  '123e3'     "false: the notation is not recognized"
} do: [ :a | a realIsNumeric printNl ]


        define('nchk(str)') :(nchk_end)
nchk    convert(str,'real') :s(return)f(freturn)
nchk_end

*       # Wrapper for testing
        define('isnum(str)') :(isnum_end)
isnum   isnum = 'F'; isnum = nchk(str) 'T'
        isnum = isnum ': ' str :(return)
isnum_end

*       # Test and display
        output = isnum('123')
        output = isnum('123.0')
        output = isnum('123.')
        output = isnum('-123')
        output = isnum('3.14159')
        output = isnum('1.2.3')
        output = isnum('abc')
        output = isnum('A440')
end


DECLARE @s VARCHAR(10)
SET @s = '1234.56'

print isnumeric(@s) --prints 1 if numeric, 0 if not.

IF isnumeric(@s)=1 BEGIN print 'Numeric' END
ELSE print 'Non-numeric'


--#SET TERMINATOR @

CREATE OR REPLACE FUNCTION IS_NUMERIC (
  IN STRING VARCHAR(10)
 ) RETURNS SMALLINT
 -- ) RETURNS BOOLEAN
 BEGIN
  DECLARE RET SMALLINT;
  -- DECLARE RET BOOLEAN;
  DECLARE TMP INTEGER;
  DECLARE CONTINUE HANDLER FOR SQLSTATE '22018'
    SET RET = 1;
    -- SET RET = FALSE;

  SET RET = 0;
  --SET RET = TRUE;
  SET TMP = INTEGER(STRING);
  RETURN RET;
 END @

VALUES IS_NUMERIC('5')@
VALUES IS_NUMERIC('0')@
VALUES IS_NUMERIC('-1')@
VALUES IS_NUMERIC('A')@
VALUES IS_NUMERIC('-')@
VALUES IS_NUMERIC('z')@
VALUES IS_NUMERIC('')@
VALUES IS_NUMERIC(' ')@


(* this function only recognizes integers in decimal format *)
fun isInteger s = case Int.scan StringCvt.DEC Substring.getc (Substring.full s) of
   SOME (_,subs) => Substring.isEmpty subs
 | NONE          => false

fun isReal s = case Real.scan Substring.getc (Substring.full s) of
   SOME (_,subs) => Substring.isEmpty subs
 | NONE          => false

fun isNumeric s = isInteger s orelse isReal s


func isNumeric(a: String) -> Bool {
  return Double(a) != nil
}


proc isNumeric str {string is double -strict $str}


prog:   ignore(<< >>)
        parse(line)\prog
        parse(error)\prog;
line:   number *;
number: ignore(none)
        sign float (exp | ={})
        = { < True: > 3 2 1 * };
sign:   <+>={} | <->={<->} | ={};
float:  int ( <.> decim = { 2 <.> 1 } | = { 1 } )
     |  <.> int = { <.> 1 };
int:    smark any(digit) string(digit) scopy;
decim:  smark string(digit) scopy;
exp:    any(<<eE>>) sign int = { <e> 2 1 };

error:  smark any(nonl) ignore(none) string(nonl) scopy * = { <False: > 1 * };

digit:  <<0123456789>>;
none:   <<>>;
nonl:   !<<
>>;


[ ( string -- flag )
  >number nip ] is isNumeric

( Some tests )
decimal
" 100" isNumeric .     ( succeeds, 100 is a valid decimal integer )
" 100.21" isNumeric .  ( fails, 100.21 is not an integer)
" a" isNumeric .       ( fails, 'a' is not a valid integer in the decimal base )
" $a" isNumeric .      ( succeeds, because $ is a valid override prefix )
                       ( denoting that the following character is a hexadecimal number )


DECLARE FUNCTION isnumeric$

LET true$ = "True"
LET false$ = "False"
LET s$ = "-152.34"
PRINT s$, " => "; isnumeric$(s$)
LET s$ = "1234.056789"
PRINT s$, " => "; isnumeric$(s$)
LET s$ = "1234.56"
PRINT s$, " => "; isnumeric$(s$)
LET s$ = "021101"
PRINT s$, " => "; isnumeric$(s$)
LET s$ = "Dog"
PRINT s$, " => "; isnumeric$(s$)
LET s$ = "Bad125"
PRINT s$, " => "; isnumeric$(s$)
LET s$ = "-0177"
PRINT s$, " => "; isnumeric$(s$)
LET s$ = "+123abcd.ef"
PRINT s$, " => "; isnumeric$(s$)
LET s$ = "54321"
PRINT s$, " => "; isnumeric$(s$)
LET s$ = "123xyz"
PRINT s$, " => "; isnumeric$(s$)
LET s$ = "xyz"
PRINT s$, " => "; isnumeric$(s$)
FUNCTION isnumeric$(s$)
    LET optchar$ = ""
    IF len(s$) = 0 then
       LET isnumeric$ = false$
       EXIT FUNCTION
    END IF
    IF pos(s$,"+") > 1 then
       LET isnumeric$ = false$
       EXIT FUNCTION
    END IF
    IF pos(s$,"-") > 1 then
       LET isnumeric$ = false$
       EXIT FUNCTION
    END IF
    LET ndex = 0
    FOR i = 1 to len(s$)
        SELECT CASE ord((s$)[i:i+1-1][1:1])
        CASE 43                   !+
        CASE 45                   !-
        CASE 46                   !.
             IF ndex = 1 then
                LET isnumeric$ = false$
                EXIT FUNCTION
             END IF
             LET ndex = 1
        CASE 48 to 57             !0 a 9
        CASE else
             IF pos(optchar$,((s$)[i:i+1-1])) = 0 then
                LET isnumeric$ = false$
                EXIT FUNCTION
             END IF
        END SELECT
    NEXT i
    LET isnumeric$ = true$
END FUNCTION
END


#!/bin/bash
isnum() {
  printf "%f" $1 >/dev/null 2>&1
}

check() {
  if isnum $1
  then
     echo "$1 is numeric"
  else
     echo "$1 is NOT numeric"
  fi
}

check 2
check -3
check +45.44
check -33.332
check 33.aa
check 3.3.3


def isnum (string str)
	try
		double str
		return true
	catch valueerror
		return false
	end try
end isnum


Sub Main()
    Debug.Print Is_Numeric("")
    Debug.Print Is_Numeric("-5.32")
    Debug.Print Is_Numeric("-51,321 32")
    Debug.Print Is_Numeric("123.4")
    Debug.Print Is_Numeric("123,4")
    Debug.Print Is_Numeric("123;4")
    Debug.Print Is_Numeric("123.4x")
End Sub

Private Function Is_Numeric(s As String) As Boolean
Dim Separat As String, Other As String
    Separat = Application.DecimalSeparator
    Other = IIf(Separat = ",", ".", ",")
    Is_Numeric = IsNumeric(Replace(s, Other, Separat))
End Function


:IS_NUMERIC:
if (Num_Eval(SUPPRESS)==0 && Cur_Char != '0') {
    Return(FALSE)
} else {
    Return(TRUE)
}


Dim Value As String = "+123"

If IsNumeric(Value) Then
    PRINT "It is numeric."
End If


import strconv

fn is_numeric(s string) bool {
	strconv.atof64(s) or {
		return false
	}
	return true
}

fn main() {
    println("Are these strings numeric?")
    strings := ["1", "3.14", "-100", "1e2", "NaN", "rose", "0xff", "0b110"]
    for s in strings {
        println("  ${s:4} -> ${is_numeric(s)}")
    }
}


import "/fmt" for Fmt

System.print("Are these strings numeric?")

for (s in ["1", "3.14", "-100", "1e2", "NaN", "0xaf", "rose"]) {
    var  i = Num.fromString(s) // returns null if 's' is not numeric
    System.print("  %(Fmt.s(4, s)) -> %((i != null) ? "yes" : "no")")
}


(DEFUN NUMERICP (X)
    (IF (STRING->NUMBER X) T))


fcn isNum(text){
   try{ text.toInt(); True }
   catch{ try{ text.toFloat(); True }
          catch{ False }
   }
}


program: numeric
  case: 1   input: '1'      output: true
  case: 2   input: '-3'     output: true
  case: 3   input: '22.7'   output: true
  case: 4   input: 'a'      output: false
  case: 5   input: 'Fred'   output: false
  case: 6   input: ''       output: false


BEGIN # find all primes with strictly decreasing digits                      #
    PR read "primes.incl.a68" PR                   # include prime utilities #
    PR read "rows.incl.a68"   PR                   # include array utilities #
    [ 1 : 512 ]INT primes;         # there will be at most 512 (2^9) primes  #
    INT p count := 0;                        # number of primes found so far #
    FOR d1 FROM 0 TO 1 DO
        INT n1 = IF d1 = 1 THEN 9 ELSE 0 FI;
        FOR d2 FROM 0 TO 1 DO
            INT n2 = IF d2 = 1 THEN ( n1 * 10 ) + 8 ELSE n1 FI;
            FOR d3 FROM 0 TO 1 DO
                INT n3 = IF d3 = 1 THEN ( n2 * 10 ) + 7 ELSE n2 FI;
                FOR d4 FROM 0 TO 1 DO
                    INT n4 = IF d4 = 1 THEN ( n3 * 10 ) + 6 ELSE n3 FI;
                    FOR d5 FROM 0 TO 1 DO
                        INT n5 = IF d5 = 1 THEN ( n4 * 10 ) + 5 ELSE n4 FI;
                        FOR d6 FROM 0 TO 1 DO
                            INT n6 = IF d6 = 1 THEN ( n5 * 10 ) + 4 ELSE n5 FI;
                            FOR d7 FROM 0 TO 1 DO
                                INT n7 = IF d7 = 1 THEN ( n6 * 10 ) + 3 ELSE n6 FI;
                                FOR d8 FROM 0 TO 1 DO
                                    INT n8 = IF d8 = 1 THEN ( n7 * 10 ) + 2 ELSE n7 FI;
                                    FOR d9 FROM 0 TO 1 DO
                                        INT n9 = IF d9 = 1 THEN ( n8 * 10 ) + 1 ELSE n8 FI;
                                        IF n9 > 0 THEN
                                            IF is probably prime( n9 ) THEN
                                                # have a prime with strictly descending digits #
                                                primes[ p count +:= 1 ] := n9
                                            FI
                                        FI
                                    OD
                                OD
                            OD
                        OD
                    OD
                OD
            OD
        OD
    OD;
    QUICKSORT primes FROMELEMENT 1 TOELEMENT p count;     # sort the primes #
    # display the primes                                                    #
    FOR i TO p count DO
        print( ( "  ", whole( primes[ i ], -8 ) ) );
        IF i MOD 10 = 0 THEN print( ( newline ) ) FI
    OD
END


descending: @[
    loop 1..9 'a [
        loop 1..dec a 'b [
            loop 1..dec b 'c [
                loop 1..dec c 'd [
                    loop 1..dec d 'e [
                        loop 1..dec e 'f [
                            loop 1..dec f 'g [
                                loop 1..dec g 'h [
                                    loop 1..dec h 'i -> @[a b c d e f g h i]
                                    @[a b c d e f g h]]
                            @[a b c d e f g]]
                        @[a b c d e f]]
                    @[a b c d e]]
                @[a b c d]]
            @[a b c]]
        @[a b]]
    @[a]]
]

descending: filter descending 'd -> some? d 'n [not? positive? n]
descending: filter descending 'd -> d <> unique d
descending: sort map descending 'd ->  to :integer join to [:string] d

loop split.every:10 select descending => prime? 'row [
    print map to [:string] row 'item -> pad item 8
]


# syntax: GAWK -f DESCENDING_PRIMES.AWK
BEGIN {
    start = 1
    stop = 99999999
    for (i=start; i<=stop; i++) {
      leng = length(i)
      flag = 1
      for (j=1; j<leng; j++) {
        if (substr(i,j,1) <= substr(i,j+1,1)) {
          flag = 0
          break
        }
      }
      if (flag) {
        if (is_prime(i)) {
          printf("%9d%1s",i,++count%10?"":"\n")
        }
      }
    }
    printf("\n%d-%d: %d descending primes\n",start,stop,count)
    exit(0)
}
function is_prime(n,  d) {
    d = 5
    if (n < 2) { return(0) }
    if (n % 2 == 0) { return(n == 2) }
    if (n % 3 == 0) { return(n == 3) }
    while (d*d <= n) {
      if (n % d == 0) { return(0) }
      d += 2
      if (n % d == 0) { return(0) }
      d += 4
    }
    return(1)
}


// Descending primes. Nigel Galloway: April 19th., 2022
[2;3;5;7]::List.unfold(fun(n,i)->match n with []->None |_->let n=n|>List.map(fun(n,g)->[for n in n..9->(n+1,i*n+g)])|>List.concat in Some(n|>List.choose(fun(_,n)->if isPrime n then Some n else None),(n|>List.filter(fst>>(>)10),i*10)))([(4,3);(2,1);(8,7)],10)
  |>List.concat|>List.sort|>List.iter(printf "%d "); printfn ""


USING: grouping grouping.extras math math.combinatorics
math.functions math.primes math.ranges prettyprint sequences
sequences.extras ;

9 1 [a,b] all-subsets [ reverse 0 [ 10^ * + ] reduce-index ]
[ prime? ] map-filter 10 "" pad-groups 10 group simple-table.


#include "isprime.bas"
#include "sort.bas"

Dim As Double t0 = Timer
Dim As Integer i, n, tmp, num, cant
Dim Shared As Integer matriz(512)
For i = 0 To 511
    n = 0
    tmp = i
    num = 9
    While tmp
        If tmp And 1 Then n = n * 10 + num
        tmp = tmp Shr 1
        num -= 1
    Wend
    matriz(i) = n
Next i

Sort(matriz())

cant = 0
For i = 1 To Ubound(matriz)-1
    n = matriz(i)
    If IsPrime(n) Then
        Print Using "#########"; n;
        cant += 1
        If cant Mod 10 = 0 Then Print
    End If
Next i
Print Using !"\n\nThere are & descending primes."; cant
Sleep


: is-prime?   \ n -- f ;    \ Fast enough for this application
  DUP 1 AND IF  \ n is odd
    DUP 3 DO
      DUP I DUP * < IF   DROP -1 LEAVE   THEN  \ Leave loop if I**2 > n
      DUP I MOD 0=  IF   DROP  0 LEAVE   THEN  \ Leave loop if n%I is zero
    2 +LOOP  \ iterate over odd I only
  ELSE          \ n is even
    2 =         \ Returns true if n == 2.
  THEN ;

: 1digit    \ -- ;    \ Select and print one digit numbers which are prime
  10 2 ?DO
    I is-prime? IF   I 9 .r   THEN
  LOOP ;

: 2digit  \ n-bfwd digit  -- ;
  \ Generate and print primes where least significant digit < digit
  \ n-bfwd is the base number bought foward from calls to `digits` below.
  SWAP 10 * SWAP 1 ?DO
    DUP I + is-prime? IF   DUP I + 9 .r   THEN
  2 I 3 = 2* - +LOOP DROP ;  \ This generates the I sequence 1 3 7 9

: digits  \ #digits n-bfwd max-digit -- ;
  \ Print descendimg primes with #digits digits.
  2 PICK 9 > IF   ." #digits must be less than 10." 2DROP DROP EXIT   THEN
  2 PICK 1 = IF   2DROP DROP 1digit EXIT   THEN    \ One digit is special simple case
  2 PICK 2 = IF                                    \ Two digit special and
    SWAP 10 * SWAP 2 DO    \ I is 2 .. max-digit-1
      DUP I + I 2digit
    LOOP 2DROP
  ELSE
    SWAP 10 * SWAP 2 PICK ?DO  \ I is #digits .. max-digit-1
      DUP I + 2 PICK 1- SWAP I RECURSE  \ Recurse with #digits reduced by 1.
    LOOP 2DROP
  THEN ;

: descending-primes
  \ Print the descending primes.  Call digits with increasing #digits
  CR  9 1 DO   I 0 10 digits   LOOP ;


package main

import (
    "fmt"
    "rcu"
    "sort"
    "strconv"
)

func combinations(a []int, k int) [][]int {
    n := len(a)
    c := make([]int, k)
    var combs [][]int
    var combine func(start, end, index int)
    combine = func(start, end, index int) {
        if index == k {
            t := make([]int, len(c))
            copy(t, c)
            combs = append(combs, t)
            return
        }
        for i := start; i <= end && end-i+1 >= k-index; i++ {
            c[index] = a[i]
            combine(i+1, end, index+1)
        }
    }
    combine(0, n-1, 0)
    return combs
}

func powerset(a []int) (res [][]int) {
    if len(a) == 0 {
        return
    }
    for i := 1; i <= len(a); i++ {
        res = append(res, combinations(a, i)...)
    }
    return
}

func main() {
    ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})
    var descPrimes []int
    for i := 1; i < len(ps); i++ {
        s := ""
        for _, e := range ps[i] {
            s += string(e + '0')
        }
        p, _ := strconv.Atoi(s)
        if rcu.IsPrime(p) {
            descPrimes = append(descPrimes, p)
        }
    }
    sort.Ints(descPrimes)
    fmt.Println("There are", len(descPrimes), "descending primes, namely:")
    for i := 0; i < len(descPrimes); i++ {
        fmt.Printf("%8d ", descPrimes[i])
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Println()
}


using Combinatorics
using Primes

function descendingprimes()
    return sort!(filter(isprime, [evalpoly(10, x)
       for x in powerset([1, 2, 3, 4, 5, 6, 7, 8, 9]) if !isempty(x)]))
end

foreach(p -> print(rpad(p[2], 10), p[1] % 10 == 0 ? "\n" : ""), enumerate(descendingprimes()))


local function is_prime(n)
  if n < 2 then return false end
  if n % 2 == 0 then return n==2 end
  if n % 3 == 0 then return n==3 end
  for f = 5, n^0.5, 6 do
    if n%f==0 or n%(f+2)==0 then return false end
  end
  return true
end

local function descending_primes()
  local digits, candidates, primes = {9,8,7,6,5,4,3,2,1}, {0}, {}
  for i = 1, #digits do
    for j = 1, #candidates do
      local value = candidates[j] * 10 + digits[i]
      if is_prime(value) then primes[#primes+1] = value end
      candidates[#candidates+1] = value
    end
  end
  table.sort(primes)
  return primes
end

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


#!/usr/bin/perl

use strict; # https://rosettacode.org/wiki/Descending_primes
use warnings;
use ntheory qw( is_prime );

print join('', sort map { sprintf "%9d", $_ } grep /./ && is_prime($_),
  glob join '', map "{$_,}", reverse 1 .. 9) =~ s/.{45}\K/\n/gr;


with javascript_semantics
function descending_primes(sequence res, atom p=0, max_digit=9)
    for d=1 to max_digit do
        atom np = p*10+d
        if odd(d) and is_prime(np) then res &= np end if
        res = descending_primes(res,np,d-1)
    end for
    return res
end function

sequence r = sort(descending_primes({2})),
--sequence r = descending_primes({2}),
         j = join_by(r,1,11," ","\n","%8d")
printf(1,"There are %,d descending primes:\n%s\n",{length(r),j})


import util.

main =>
  DP = [N : S in power_set("987654321"), S != [], N = S.to_int, prime(N)].sort,
  foreach({P,I} in zip(DP,1..DP.len))
    printf("%9d%s",P,cond(I mod 10 == 0,"\n",""))
  end,
  nl,
  println(len=DP.len).


put (flat 2, 3, 5, 7, sort +*, gather (3..9).map: &recurse ).batch(10)».fmt("%8d").join: "\n";

sub recurse ($str) {
    .take for ($str X~ (1, 3, 7)).grep: { .is-prime && [>] .comb };
    recurse $str × 10 + $_ for 2 ..^ $str % 10;
}


load "stdlibcore.ring"

limit = 1000
row = 0

for n = 1 to limit
    flag = 0
    strn = string(n)
    if isprime(n) = 1
       for m = 1 to len(strn)-1
           if number(substr(strn,m)) < number(substr(strn,m+1))
              flag = 1
           ok
       next
       if flag = 1
          row++
          see "" + n + " "
       ok
       if row % 10 = 0
          see nl
       ok
    ok
next


func primes_with_descending_digits(base = 10) {

    var list = []
    var digits = @(1..^base)

    var end_digits = digits.grep { .is_coprime(base) }
    list << digits.grep { .is_prime && !.is_coprime(base) }...

    for k in (0 .. digits.end) {
        digits.combinations(k, {|*a|
            var v = a.digits2num(base)
            end_digits.each {|d|
                var n = (v*base + d)
                next if ((n >= base) && (a[0] <= d))
                list << n if n.is_prime
            }
        })
    }

    list.sort
}

var base = 10
var arr = primes_with_descending_digits(base)

say "There are #{arr.len} descending primes in base #{base}.\n"

arr.each_slice(8, {|*a|
    say a.map { '%9s' % _ }.join(' ')
})


import "./perm" for Powerset
import "./math" for Int
import "./seq" for Lst
import "./fmt" for Fmt

var ps = Powerset.list((9..1).toList)
var descPrimes = ps.skip(1).map { |s| Num.fromString(s.join()) }
                           .where { |p| Int.isPrime(p) }
                           .toList
                           .sort()
System.print("There are %(descPrimes.count) descending primes, namely:")
for (chunk in Lst.chunks(descPrimes, 10)) Fmt.print("$8s", chunk)


include xpllib;         \provides IsPrime and Sort

int I, N, Mask, Digit, A(512), Cnt;
[for I:= 0 to 511 do
    [N:= 0;  Mask:= I;  Digit:= 9;
    while Mask do
        [if Mask&1 then
            N:= N*10 + Digit;
        Mask:= Mask>>1;
        Digit:= Digit-1;
        ];
    A(I):= N;
    ];
Sort(A, 512);
Cnt:= 0;
Format(9, 0);
for I:= 1 to 511 do     \skip empty set
    [N:= A(I);
    if IsPrime(N) then
        [RlOut(0, float(N));
        Cnt:= Cnt+1;
        if rem(Cnt/10) = 0 then CrLf(0);
        ];
    ];
]


T Triangle
   (Float, Float) p1, p2, p3

   F (p1, p2, p3)
      .p1 = p1
      .p2 = p2
      .p3 = p3

   F String()
      R ‘Triangle: #., #., #.’.format(.p1, .p2, .p3)

   F.const det2D()
      R .p1[0] * (.p2[1] - .p3[1])
      + .p2[0] * (.p3[1] - .p1[1])
      + .p3[0] * (.p1[1] - .p2[1])

F checkTriWinding(Triangle &t; allowReversed)
   V detTri = t.det2D()
   I detTri < 0.0
      assert(allowReversed, ‘Triangle has wrong winding direction’)
      swap(&t.p2, &t.p3)

F boundaryCollideChk(Triangle t, Float eps)
   R t.det2D() < eps

F boundaryDoesntCollideChk(Triangle t, Float eps)
   R t.det2D() <= eps

F triTri2D(Triangle &t1, &t2; eps = 0.0, allowReversed = 0B, onBoundary = 1B)
   checkTriWinding(&t1, allowReversed)
   checkTriWinding(&t2, allowReversed)
   V chkEdge = I onBoundary {:boundaryCollideChk} E :boundaryDoesntCollideChk
   V lp1 = [t1.p1, t1.p2, t1.p3]
   V lp2 = [t2.p1, t2.p2, t2.p3]

   L(i) 3
      V j = (i + 1) % 3
      I chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) &
        chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) &
        chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)
         R 0B

   L(i) 3
      V j = (i + 1) % 3
      I chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) &
        chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) &
        chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)
         R 0B

   R 1B

F overlap(Triangle &t1, &t2; eps = 0.0, allowReversed = 0B, onBoundary = 1B)
   I triTri2D(&t1, &t2, eps, allowReversed, onBoundary)
      print(‘overlap’)
   E
      print(‘do not overlap’)

V t1 = Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 5.0))
V t2 = Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 6.0))
print(t1" and\n"t2)
overlap(&t1, &t2)
print()

t1 = Triangle((0.0, 0.0), (0.0, 5.0), (5.0, 0.0))
t2 = t1
print(t1" and\n"t2)
overlap(&t1, &t2, 0.0, 1B)
print()

t1 = Triangle((0.0, 0.0), (5.0, 0.0), (0.0, 5.0))
t2 = Triangle((-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0))
print(t1" and\n"t2)
overlap(&t1, &t2)
print()

t1.p3 = (2.5, 5.0)
t2 = Triangle((0.0, 4.0), (2.5, -1.0), (5.0, 4.0))
print(t1" and\n"t2)
overlap(&t1, &t2)
print()

t1 = Triangle((0.0, 0.0), (1.0, 1.0), (0.0, 2.0))
t2 = Triangle((2.0, 1.0), (3.0, 0.0), (3.0, 2.0))
print(t1" and\n"t2)
overlap(&t1, &t2)
print()

t2 = Triangle((2.0, 1.0), (3.0, -2.0), (3.0, 4.0))
print(t1" and\n"t2)
overlap(&t1, &t2)
print()

t1 = Triangle((0.0, 0.0), (1.0, 0.0), (0.0, 1.0))
t2 = Triangle((1.0, 0.0), (2.0, 0.0), (1.0, 1.1))
print(t1" and\n"t2)
print(‘which have only a single corner in contact, if boundary points collide’)
overlap(&t1, &t2)
print()

print(t1" and\n"t2)
print(‘which have only a single corner in contact, if boundary points do not collide’)
overlap(&t1, &t2, 0.0, 0B, 0B)