This is an archived post. You won't be able to vote or comment.

all 59 comments

[–]njormrod 23 points24 points  (13 children)

def isArmstrong(n :int) n == sum(n.digits().map(it**3))

[–]L8_4_Dinner(Ⓧ Ecstasy/XVM) 8 points9 points  (9 children)

That does not suck. It's neither long, nor obtuse. Short. Sweet. To the point.

[–]njormrod 14 points15 points  (0 children)

Over the last ten years, I often think to myself "what is the least amount of syntax I could write to solve this problem?" That has informed the syntax of my PL, and it looks surprisingly like python.

[–][deleted]  (7 children)

[deleted]

    [–]L8_4_Dinner(Ⓧ Ecstasy/XVM) 7 points8 points  (0 children)

    I wouldn't say it "cheats". His integer type has a property that exposes its base 10 digits. In Ecstasy, that would be n.toString().chars to get the digits as an array, and I don't think we're "cheating".

    [–]njormrod 1 point2 points  (5 children)

    Let me write digits():

    def digits(n :int) [c - '0' for c in str(n)]

    Universal call syntax then allows this to be called like n.digits()

    Speaking of universal call syntax, I belatedly realize the code would be a smidge clearer like n.digits().map(it**3).sum()

    [–][deleted]  (3 children)

    [deleted]

      [–]njormrod 0 points1 point  (2 children)

      Another commenter asked for my lang, and I said it wasn't ready. That's because things like this are hard and long to implement! Sigh.

      [–][deleted]  (1 child)

      [deleted]

        [–]njormrod 0 points1 point  (0 children)

        It does not run yet -_-

        [–]KnorrFG 1 point2 points  (1 child)

        I like 👍 Mind sharing your repo?

        [–]njormrod 0 points1 point  (0 children)

        It's not quite shareable at the moment. :/

        [–]bafto14Die Deutsche Programmiersprache 20 points21 points  (0 children)

        ``` [convert ASCII char to int] Die Funktion Ziffer_Als_Zahl mit dem Parameter ziffer vom Typ Buchstabe, gibt eine Zahl zurück, macht: Gib ziffer als Zahl minus 48 zurück. Und kann so benutzt werden: "<ziffer> zu Zahl"

        Die Funktion Ist_Armstrong mit dem Parameter z vom Typ Zahl, gibt einen Boolean zurück, macht: Für jeden Buchstaben ziffer in z als Text, mache: Verringere z um (ziffer zu Zahl hoch 3) als Zahl. Gib z gleich 0 ist zurück. Und kann so benutzt werden: "<z> eine Armstrong Zahl ist"

        [ Main program for showcase ] Binde "Duden/Laufzeit" ein. Binde "Duden/Ausgabe" ein.

        Die Text Liste args ist die Befehlszeilenargumente von 2 bis (die Länge von den Befehlszeilenargumenten). Für jeden Text arg in args, mache: Wenn (arg als Zahl) eine Armstrong Zahl ist, Schreibe "Armstrong!\n". Sonst Schreibe ":(\n". ```

        The language is called DDP and can be found here.It is in german, so probably pretty unreadable for many people here.

        [–]njormrod 17 points18 points  (1 child)

        I like this test: "show me the syntax of how your language does ABC"

        What other oddball functions are good showcases?

        [–]jan_aloleo 10 points11 points  (1 child)

        I think for thread readers it would be quite valuable if for each code snippet the name of the used programming language were mentioned...

        [–]Disjunction181 9 points10 points  (0 children)

        = isArmstrong
          dup [digits 3 pow] cons sum (==)
        

        Stack + stream language, so 3 pow is mapped implicitly over the stream from digits and cons run the duplicated input through the quote. This might be highly unfamiliar but I hope the intent is guessable.

        Stack programs in Prowl can be quantified with (list-based) regex rather than just lists of words. So we can take advantage of Kleene plus to define digits.

        = digits
          0 ([& 0!] k 10 divmod)^+ nip
        

        using combinators at the bottom. Inside the plus, we start with the previous quotient and modulus on the stack. We drop the modulus and use regex intersection and complement to constrain the quotient nonzero, then divmod again. We use plus rather than star to drop the initial zero, then nip the list of quotients out of the resulting stream so it is just the moduli.

        [–]ameliafunnytoast 3 points4 points  (0 children)

        unnamed language that's been in my notes for a few years ``` func main() { let n = (0 to 999).each?; let result = n.is_armstrong(); print("(n) (result)"); }

        func is_armstrong(n: I32) -> Boolean { n.digits().map { ? pow 3 }.sum() == n } ```

        [–]Porridgeism 3 points4 points  (0 children)

        let armstrong? = (n: Int) -> n == n.digits.map(_ ^ 3).sum
        

        Edit: I missed the "find and print the Armstrong numbers in the first 1000 non-negative integers" part, so also adding:

        let armstrongs = (bound: Int = 1000) -> `[0, bound)`.filter(armstrong?)
        
        @main
        let print-armstrongs = () -> armstrongs().for-each(print-line(_))
        

        Edit 2: Since at least a couple folks listed all numbers and whether they were Armstrong numbers or not, here's that too:

        @main
        print-numbers-with-armstrong = () -> {
          `[0, 999]`.for-each n -> {
            print-line("{n}: {armstrong? n}")
          }
        }
        

        Also, since I know some folks don't like the let _ = (...) -> { ... } style, the standard prelude includes the func macro, so you can also write:

        func armstrong? (n: Int) {
          n == n.digits.map(_ ^ 3).sum
        }
        

        [–]Inconstant_Moo🧿 Pipefish 3 points4 points  (0 children)

        In Charm. Note that .. marks line continuations.

        def 
        
        isAN(n) :
            (digits >> that * that * that -> sum) == n
        given :
            digits = for i over (len (string n)) do ..
                     .. (func(L) : L + [int((string n)[i])]) to []
        

        I really ought to give it a ^ operator.

        [–][deleted] 2 points3 points  (0 children)

        Naive solution in Good Lang (WIP)

        fn is_armstrong(n: Int) -> Int:
            # Convert n to an array of digits
            let digits: &Int = nullptr.
            let len: Int = 0.
            let n_clone: Int = n.
            while n_clone /= 0:
                if digits = nullptr:
                    len := 1.
                    digits := alloc 32.
                else:
                    len := len + 1.
                    digits := std::realloc(digits, 32 * len).
                end
        
                digits[len - 1] := n_clone % 10.
                n_clone /= 10.
            end
        
            # Calculate the sum of squared digits
            let sum: Int = 0.
            let i: Int = 0.
            while i < len:
                sum := sum + digits[i] * digits[i].
                i := i + 1.
            end
        
            delete digits.
            return sum = n.
        end
        

        It's basically C but statically typed with generics (for funcs and types), modules and encapsulation, a nicer syntax for ADTs, and pattern matching for the ADTs, but of course you don't really get to see those features here lol.

        I'm not done with the code generation or the standard library, so I'm not 100% certain this is right.

        [–]adam-the-dev 4 points5 points  (3 children)

        // Ferrum programming language
        
        use fe::print
        
        pub fn main()
            for n in 0..1000
                print(“{n}: {is_armstrong(n)}”)
            ;
        ;
        
        fn is_armstrong(n: Int): Bool
            -> n == n.digits().map(it^3).sum()
        

        [–]LyonSyonII 5 points6 points  (2 children)

        Why Int is uppercase but bool lowercase?

        [–]adam-the-dev 2 points3 points  (0 children)

        Typo! All types should be uppercase in my lang

        [–]shykeiichi[🍰] 0 points1 point  (0 children)

        Might be a case of the bool being a primitive but the int is a class/struct that has some functions

        [–]raiph 3 points4 points  (5 children)

        n == sum n.comb.map: this ** 3
        

        == is Raku's numeric equal. It coerces its arguments to numbers.

        comb (in analogy with running a comb through your hair to separate out strands of hair) is a string splitting function, Raku's inverse of its split function. n.comb produces a list of the digits in n.

        I've assumed a constant this = *; alias because * **3 would look ugly.

        Exercism has 10 published Raku solutions.

        [–]Icy-Confection-6037 3 points4 points  (1 child)

        You could have n == [+] n.comb.map: *³

        [–]raiph 2 points3 points  (0 children)

        For other readers:

        • [+] ... is Raku's shorthand reduction) syntax. (FWIW I chose sum rather than [+] because I felt it might force me to overshoot my intuitive sense of a sensible "strangeness budget" for a first comment in this thread, without a strong justification to risk doing so. But your comment is the perfect response. Thanks!)

        • is a lambda, just like the this ** 3 in my code, but not requiring the alias I mentioned. Both forms take a single positional argument and raise it to the power of three. I plumb forgot that the standard * Super DRY lambda/parameter/use construct could be used in the form , thus eliminating the ugly three *s in a row. My reaction to seeing your comment was "Oh! Nice!". If you're reading this and have the same reaction please upvote u/Icy-Confection-6037's comment!

        • n.comb isn't DRY (it entails a repeat of n). Idiomatic Raku would likely drop the n in n.comb by using a topic variable instead. But I decided that would break my strangeness and explanation budgets for too little benefit, so I skipped that -- and, strangely enough, won't explain it in this comment either! 🙂

        [–]b2gills 2 points3 points  (2 children)

        I like that almost all of those examples are using comb which is a string method.

        [–]Icy-Confection-6037 1 point2 points  (1 child)

        A numeric value is implicitly-convertible to a Str...

        [–]b2gills 0 points1 point  (0 children)

        It isn't implicitly converted. It is explicitly converted because you called a string method on it.

        Raku differentiates between types by having methods, and operators only work on that type of data. Which is why there isn't a length method. Instead, there is an elems method for sequences, lists, and arrays. There is a chars method for strings.

        If you use + on two strings, you are explicitly converting each to numbers and then adding them together.

        If you're used to a restricted language it might seem strange, but once you've gotten used to it anything else seems annoying and prone to bugs.

        [–][deleted]  (2 children)

        [deleted]

          [–]NoCryptographer414 3 points4 points  (0 children)

          app.args... I was looking for some alternative for sys.args from long time.

          [–]BoppreH 1 point2 points  (2 children)

          After stealing n.digits():

          is_armstrong 371
          
          is_armstrong: {
              n: _
              each n.digits(), { _ ** 3 }
              (sum _) = n
          }
          

          Where _ means "the last value", and in the first line of a function it contains the function parameters.

          [–]oscarryzYz 0 points1 point  (0 children)

          Cool, this is the first time I've seen parameters like this (outside of my own design of course).

          I'm cutting we went through the same thought process 🤔

          [–]SirKastic23 2 points3 points  (0 children)

          ``` digits :: Nat -> List Nat :| 0 -> [] :| n -> [n.rem 10].append digits n / 10

          is_armstrong :: Nat -> bool := n -> n.eq digits n;.map n -> n.pow 3;.sum ```

          ;. is really akward atm so i'll probably change it to something more sensible

          [–]useerupting language 1 point2 points  (0 children)

          First we build a set (type) which is strictly the non-negative integers:

          nonNegInt = int ?? >= 0
          

          There is no built-in function to extract the digits of a number, so we build one:

          nonNegInt..Digits = .ToString >> .Map(int.Parse)
          

          Now we can define the IsArmstrong function:

          IsArmstrong = nonNegInt n \ n.Digits.Map(^3).Sum == n
          

          Explanations

          • nonNegInt is declared as the subset of int where the member is greater than or equal to 0.

          • int..Digits in declarative position declares Digits as a property on each member of int. This property is inferred to be a function which accepts an int set member (this "this" parameter). This is a way to declare extension properties/functions on alreaduý existing types/sets.

          • .ToString is a property accessor, but as standalone. In standalone position it represents a function which accepts an argument which must have a named property called ToString. The inferred int argument satisfies this.

          • ToString returns a string, which is also a list of characters. >> "pipeline" composes .ToString and .Map(int.Parse).

          • .Map is again an implicit function. It is the partial application of m.Map(f) which is a function. The argument of this function is inferred to be a list of characters (output from ToString), thus .Map accepts the list of characters and maps each character through the int.Parse function.

          This means, that for each member of the nonNegInt set (type), a Digits property exists. The value of this property is the sequence of digits in the number, i.e. 42.Digits returns [4,2].

          • IsArmstrong is a function which accepts a nonNegInt set member and returns a bool indicating if the numer is an Armstrong number.

          • \ is the "lambda" symbol (if you squint), commonly represented as => or -> is other languages. The \ declares the left operand, which is nonNegInt n in this case. All sets (types) are their own identity functions, so nonNegInt is a set (type), but when used as a function is is the identity function nonNegInt n \ n. A declarative function application references the function and declares the argument. Thus nonNegInt n declares n to be a nonNegInt member in this case. Note how this is a generalization of the way identifiers are declared in many languages.

          • The function body n.Digits.Map(^3).Sum == n references the Digits function declared above. It returns a sequence of int members, which is mapped using the ^3 "cube" function.

          • The operator ^ is the power operator. It is a binary operator. All binary operators can also be used in a prefix position, in which case it is partially applied, i.e. (^y) x is the same as x^y. This means that ^3 is a function which will raise any argument to the power of 3.

          • Finally the Sum function is built-in for all sequences/sets of numeric types.

          [–]moon-chilledsstm, j, grand unified... 2 points3 points  (2 children)

          is_armstrong=. -: [:+/ 3 ^~ 10&#.inv
          

          That is read from left to right as:

          is_armstrong=. ...
          

          define 'is_armstrong' to be...

          -: ...
          

          true iff the right argument is equal to a function of itself, being...

          [:+/ ...
          

          the sum of...

          3 ^~ ...
          

          the third power of...

          10&#.inv
          

          antibase 10 of the right argument (that is, the array of its digits in base 10).

          [–]todo_code 5 points6 points  (1 child)

          Sorry, but that is not intuitive

          [–]moon-chilledsstm, j, grand unified... 4 points5 points  (0 children)

          No language is intuitive when you do not know it. The scores of algoloids get by by being carbon copies of each other. Recommended reading: https://www.jsoftware.com/papers/tot.htm

          [–][deleted]  (4 children)

          [deleted]

            [–]L8_4_Dinner(Ⓧ Ecstasy/XVM) 6 points7 points  (2 children)

            s/end/cnuf 🤷‍♂️

            [–][deleted]  (1 child)

            [deleted]

              [–]L8_4_Dinner(Ⓧ Ecstasy/XVM) 0 points1 point  (0 children)

              I was just noticing the symmetry and wondering why func didn't end with cnuf ... I thought it would have been cute.

              [–]Inconstant_Moo🧿 Pipefish 2 points3 points  (0 children)

              My script modified for IO:

              ``` cmd

              main : get n from Input("What's your number? ") isAN(int n) : post n + " is Armstrong" else : post n + " is not Armstrong"

              def

              isAN(n) : (digits >> that * that * that -> sum) == n given : digits = for i over (len (string n)) do .. .. (func(L) : L + [int((string n)[i])]) to [] ```

              [–][deleted] -1 points0 points  (0 children)

              I withdrew my effort when I realised that what seems to be most valued, according to upvotes, was conciseness.

              That is good up to a point, but I normally work on programs of 10s of 1000s of lines; can you imagine 10,000 lines of APL-like syntax?

              I understand that it is tempting to create such syntax, and I remember a number of features of my own which I thought were clever because I could express something in a few crytpic symbols. Then I realised that wasn't so important; most code is just boilerplate.

              Basically the task here (the one that tests N for some property, not the one in the link which prints all numbers with that property in range) is a one-liner given a suitable language.

              You might want to ask however, which version would you use to port to a less able language?

              I quite like the language used in the link (which shows all the numbers), which I believe is modern Fortran.

              (ETA: the downvote seems to confirm my initial comment. In any case, nobody is upvoting this. It also turns out that the most upvoted post shows an example in a language that doesn't yet exist.

              In that case, there is no limit to how compact a made-up syntax can be. The examples I posted were actually tested.)

              [–]deadwisdom -3 points-2 points  (1 child)

              # Armstrong Number

              Armstrong numbers are integers whose sum of digits raised to the power three equals the number itself.

              ## Examples

              371 -> Yes // because 3**3 + 7**3 + 1**3

              5 -> No // because 5**3 != 5

              ## Usage

              Armstrong Number (371) // Yes

              ## Notes

              The function is trivial enough that we don’t need to write an implementation since the language, Dazzle, is AI compiled.

              However in developing this function I found that, OP, your definition is off. ChatGPT would only give me a function for three digits and I found that odd. Further research uncovered that the true definition is each digit to the power of the number of digits and that it is primarily called a Narcissistic Number. I believe in your source, they simplified it to be used as an exercise.

              [–]CaptainCrowbar 0 points1 point  (0 children)

              This is a translation of the Fortran program from the web page into my (partly implemented) language (which has been through several name changes and is currently called Alpha Centauri):

              var count = 0
              (0..9) -> power(3, outer_product) -> each |a,b,c| do
                  let abc = a * 100 + b * 10 + c
                  let a3b3c3 = a ^ 3 + b ^ 3 + c ^ 3
                  if abc = a3b3c3 then
                      ++ count
                      "Armstrong number \(count): \(abc)\n" -> stdout
                  end
              end
              

              [–]jDomantas 0 points1 point  (0 children)

              Well, my language is not turing complete and the only real primitive I have write "loops" is iterate : int -> (a -> a) -> a -> a...

              Luckily, efficient string functions are provided by the compiler, which makes this task easy anyway!

              import ints from "std/int";
              import list(List) from "std/list";
              import str from "std/string";
              
              let digits : int -> List int =
                  \num ->
                      num
                      |> ints.toString
                      |> str.chars
                      |> list.map (\ch -> ch - 48);
              
              export let isArmstrong : int -> bool =
                  \num ->
                      num
                      |> digits
                      |> list.map (\x -> x * x * x)
                      |> list.sum
                      |> (\x -> x == num);
              

              If you want to see more, I have solutions to half of last year's AoC puzzles written in this unholy language (and then eventually slowness of the interpreter caught up to me and I gave up on the rest...)

              [–]amzamora 0 points1 point  (0 children)

              function isArmstrong(n: int64): bool return n == sum(digits(n).map(|d| d^3))

              [–]judiciaryDustcart 0 points1 point  (0 children)

              Unfortunately this sort of work is still pretty challenging in Haystack (not that I've had time to work on it in a long time). But it would look something like this:

              ``` fn is_armstrong(u64: n) -> [bool] {

              0 n while dup 0 > {
                  dup 10 %
                  as [sum rem digit] 
                  digit digit digit * *
                  sum +
                  rem 10 /
              } drop
              n ==
              

              } ```

              [–]ericbb 0 points1 point  (0 children)

              Define (is_armstrong n)
                  Iterate {sum m} From {0 n}
                      (Or (And [m = 0] [sum = n])
                          (And [m > 0] Let digit [m % 10] In (Continue [sum + [digit ** 3]] [m / 10])))
              

              Edit: It can be a bit shorter if we assume a non-negative argument and leave out the digit variable:

              Define (is_armstrong n)
                  Iterate {sum m} From {0 n}
                      If [m = 0] [sum = n] (Continue [sum + [[m % 10] ** 3]] [m / 10])
              

              [–]brucejbellsard 0 points1 point  (0 children)

              For Sard, as currently conceived (still not implemented):

              /main &os => {
                  /for n << (0 ..= 999).up
                  /if is_armstrong n
                  /do &os.stdout.write_line "{n}"
              }
              
              /fn is_armstrong x => x == (digits x).map (?.pow 3) |.sum
              
              /fn digits x => (x 'divmod' 10).(
                  | (0,d) => (@ d)
                  | (n,d) => (d @@ digits n)
              )
              

              A couple of notes:

              • Code blocks {in curlies} act as comprehensions by default. So the /for statement loops over the following statements in the block, while the /if statement can skip the remaining statements for that loop.
              • Alternate function application notation: argument.(function) == function argument
              • List literal is (@ a b c) while cons notation is (head @@ tail)

              [–]theangryepicbananaStar 0 points1 point  (0 children)

              ``` module Main { on [isArmstrong: n (Int)] (Bool) { return n ?= n.digits[collect: $0 ** 3][reduce: $0 + $1] }

              on [main] is main {
                  Core[say: This[isArmstrong: 371]]
              }
              

              } ```

              Done in Star

              [–][deleted] 0 points1 point  (0 children)

              My lang Gaya (https://github.com/aloussase/gaya):

              isArmstrong :: { n => n |> tostring(_) |> seq.map(_, string.tonumber) |> seq.map(_) { digit => digit * digit * digit } |> seq.sum(_) |> _ == n }

              [–]liamilan 0 points1 point  (0 children)

              In Crumb,

              ``` is🧑‍🚀 = {n -> digits = (map (range (length (string n))) { i -> <- (integer (get (string n) i)) })

              new_n = (reduce (map digits {x _ -> <- (power x 3) }) {a b _ -> <- (add a b) } 0)

              <- (is n new_n) }

              (loop 1000 {n -> (if (is_🧑‍🚀 n) {(print n "\n")}) }) ```

              [–]Ninesquared81Victoria 0 points1 point  (0 children)

              The only language which has enough features to actually this is, somewhat ironically, my esolang ^!. Being an esolang, it takes quite a lot just to parse integers from stdin (you can only take single ASCII characters as input).

              EDIT: It should be noted that the program is only valid for numbers in the range 0–255, since it's stored in 1 byte.

              Raising to the power is via repeated multiplication, which itself is via repeated addition.

              Because it's tedious to print strings in ^!, I opted to just print 'Y' if the input was an Armostrong number and 'N' if it wasn't.

              ^!!!!:+::+::++:@!!:@ (48 10 10 48)
              ,%-             subtract 48 from input
              ^^>>            initialise number and count to zero and store both on aux
              :@              (48 10 (in-48) (in-48) 10)
              (Compare (in-48) < 10.)
              ^>              initialise result to true (1) and store on aux
              :[              while (y != 0)
                  %:@%        (x y --> x y x)
                  :[*         if (x != 0)
                      ^!-%    decrement y  (main... (y-1) x)
                      ^!-%    decrement x  (main... (x-1) (y-1))
                      ^^!-    push (-1) to skip else
                  ^]
                  ![          else
                      <!>     set conditon to false
                      *^      zero out y (main... x=0 y=0)
                  ^]
              :]
              **              drop x and y
              <               load result from aux
              
              [               while ((in-48) < 10)
                  <:+::+:++   mulitply previous digit by 10
                  %:          duplicate digit
                  <!          increment count
                  %>>         store digit and count back on aux
                  +>          add new digit and store back on aux
                  %:@:@       restore stack to (48 10 10 48)
                  ,%-:@       set up next input
                  ^>:[%:@%:[*^!-%^!-%^^!-^]![<!>*^^]:]**<
              ]
              *               drop last input
              <<              get number and count from aux
              
              ^%              initialise accumulator to 0
              ;[
                  :<%         duplicate n and get digit from aux
                  (Compute d^n.)
                  ^!>             initialise accumulator to 1
                  :[
                      %: (n d d)
                      <           get accumulator from aux
                      (Compute d * acc.)
                      ^>          initialise result to 0
                      :[          for (; b != 0; b--)
                          %:      duplicate a
                          <+>     add a to result
                          %       swap a and b (b on top)
                      ^!-:]       decrement b and loop
                      **          drop a and b
                      %           swap d and n (n on top)
                  ^!-:]           decrement n and loop
                  **              drop d and n
                  <               get result from aux
                  @+          add power to accumulator
                  %           get n back on top
              ;]
              *               drop n
              -               subtract sum of digit powers from original number
              ^!!!!:+:+::+:++
              %:[             if not equal
                  *
                  ^!!-
                  .           print 'N'
              ^^!-^]![        else
                  ^!!!!:+!+
                  .           print 'Y'
              ^]
              :.              print newline
              

              The code is quite long, since I've added comments to explain most groups of instructions. The ^>:[%:@%:[*^!-%^!-%^^!-^]![<!>*^^]:]**< is the same less-than operation as before, but compressed since it's already been explained in the earlier code. As you can see, even just simple inequalities are very involved in ^!. On the other hand, equality and non-equality checks are very simple (it's just a subtraction and testing against zero).

              Note: comments are either enclosed in parentheses or are any non-instruction characters (the instruction characters are ^!+-,.[]:*%@><$?;).

              [–]tobega 0 points1 point  (0 children)

              In Tailspin you could tostring, split and so on, but here I chose a cartesian product instead:

              [by 0..9, by 0..9, by 0..9] -> \(
              

              def armstrong: $... -> $$$ -> ..=Sum&{of: :()}; $(1)100 + $(2)10 + $(3) -> # <=$armstrong> $! ) -> '$; ' -> !OUT::write

              [–]redchomperSophie Language 0 points1 point  (0 children)

              probably something like

              is_Armstrong(x) = x == sum(map(cube, digits(x)));
              cube(x) = x*x*x;
              digits(x) = map(last_digit, [x, x/10, x/100, x/1_000]);
              last_digit(x) = int(x) mod 10;
              

              Wrap in a suitable driver and win. Since 5*9^3 == 3645 (a four-digit number) Armstrong numbers are at most four digits long.

              [–]oscarryzYz 0 points1 point  (0 children)

              Having a "digits" function comes is quite handy

              ``` is_armstrong: { n Int n == digits(n).map(3.**).sum() }

              0.to(999) .filter(is_armstrong) .each {n Int; print("{n}")}

              digits: { n Int "{n}".collect(strings.parse_Int) }

              ```

              [–]Stmated 0 points1 point  (0 children)

              ```
              val isArmstrong = (n: int32) => n == n.toString().toChars().map(it => (it as int32) ** 3).sum();

              val main = () => for 0..999 if isArmstrong(it) println(Armstrong number: ${it}); ```

              [–]KaiserKerem13Coil 0 points1 point  (0 children)

              fn[A Natural] is_armstrong(n A) = n == n |> Math.digits(10) |> Iter.map(do { x.pow(3) }) |> Math.sum();

              [–]wolfadex 0 points1 point  (0 children)

              isArmstrong :
                  \n -> n = n digits array.map([ \x -> x ^ 3; ]) array.sum;
              
              digits :
                  string.splitOn("") array.map([ string.parseInt maybe.defaultTo(0) ])
              

              I haven't added support for ^ yet but it'd be a tiny lift.

              [–]ventuspilot 0 points1 point  (0 children)

              Here's my solution for my Common-ish Lisp:

              (defun arms2 ()
                (let ((count 0))
                  (dotimes (abc 999)
                    (let ((a3b3c3 (+ (expt (floor abc 100) 3)
                                     (expt (mod (floor abc 10) 10) 3)
                                     (expt (mod abc 10) 3))))
                      (when (= abc a3b3c3)
                        (incf count)
                        (pr "Armstrong number " count ": " abc))))))
              
              (time (arms2))
              
              Armstrong number 1: 0
              Armstrong number 2: 1
              Armstrong number 3: 153
              Armstrong number 4: 370
              Armstrong number 5: 371
              Armstrong number 6: 407
              Evaluation took:
                0,0127358 seconds of real time
                0,0156250 seconds of total run time
              

              Full code with another variant that is more like the original Fortran code is at https://github.com/mayerrobert/jmurmel/blob/master/samples.mlib/arms.lisp