Skip to content

Instantly share code, notes, and snippets.

@ingydotnet
Created November 11, 2024 16:26
Show Gist options
  • Save ingydotnet/9ece4af186c6a6dcfd589c446dab9b38 to your computer and use it in GitHub Desktop.
Save ingydotnet/9ece4af186c6a6dcfd589c446dab9b38 to your computer and use it in GitHub Desktop.

YAMLScript Comparison for 'FizzBuzz'

This page compares the YAMLScript code for the Rosetta Code task 'FizzBuzz' with code from other Rosetta Code Languages.

Click on the arrow for a language below to expand its code.

This Markdown page was generated by this YAMLScript program.


About Task 'FizzBuzz'

;Task: Write a program that prints the integers from   '''1'''   to   '''100'''   (inclusive).

But: :*   for multiples of three,   print   '''Fizz'''     instead of the number; :*   for multiples of five,   print   '''Buzz'''     instead of the number; :*   for multiples of both three and five,   print   '''FizzBuzz'''     instead of the number.

The   ''FizzBuzz''   problem was presented as the lowest level of comprehension required to illustrate adequacy.

;Also see:


YAMLScript (7 lines)

!yamlscript/v0

defn main(n=100):
  each x (1 .. n): !:say
    or? _ x:
      str ((x % 3).! &&& 'Fizz'):
          ((x % 5).! &&& 'Buzz')

The Exercism Languages

8th (25 lines)
with: n

: num?  \ n f --   )
	if drop else . then ;

\ is m mod n 0? leave the result twice on the stack
: div? \ m n -- f f
	mod 0 = dup ;

: fizz? \ n -- n f
	dup 3
	div? if "Fizz" .  then ;

: buzz? \ n f -- n f
	over 5
	div? if "Buzz" .  then or ;

\ print a message as appropriate for the given number:
: fizzbuzz  \ n --
	fizz? buzz? num?
	space ;

\ iterate from 1 to 100:
' fizzbuzz 1 100 loop
cr bye
ABAP (13 lines)
DATA: tab TYPE TABLE OF string.

tab = VALUE #(
  FOR i = 1 WHILE i <= 100 (
    COND string( LET r3 = i MOD 3
                     r5 = i MOD 5 IN
                 WHEN r3 = 0 AND r5 = 0 THEN |FIZZBUZZ|
                 WHEN r3 = 0            THEN |FIZZ|
                 WHEN r5 = 0            THEN |BUZZ|
                 ELSE i ) ) ).

cl_demo_output=>write( tab ).
cl_demo_output=>display( ).
Batch-File (24 lines)
@echo off
for /L %%i in (1,1,100) do call :tester %%i
goto :eof

:tester
  set /a test = %1 %% 15
  if %test% NEQ 0 goto :NotFizzBuzz
  echo FizzBuzz
  goto :eof

:NotFizzBuzz
  set /a test = %1 %% 5
  if %test% NEQ 0 goto :NotBuzz
  echo Buzz
  goto :eof

:NotBuzz
  set /a test = %1 %% 3
  if %test% NEQ 0 goto :NotFizz
  echo Fizz
  goto :eof

:NotFizz
  echo %1
C (4 lines)
  int i = 0 ;  char B[88] ;
  while ( i++ < 100 )
    !sprintf( B, "%s%s", i%3 ? "":"Fizz", i%5 ? "":"Buzz" )
    ? sprintf( B, "%d", i ):0, printf( ", %s", B );
C++ (39 lines)
#include <iostream>
#include <chrono>

int main()
{

	int fizz = 0, buzz = 0, fizzbuzz = 0;

	bool isFizz = false;

	auto startTime = std::chrono::high_resolution_clock::now();

	for (unsigned int i = 1; i <= 4000000000; i++) {
		isFizz = false;

		if (i % 3 == 0) {
			isFizz = true;
			fizz++;
		}

		if (i % 5 == 0) {
			if (isFizz) {
				fizz--;
				fizzbuzz++;
			}
			else {
				buzz++;
			}
		}

	}

	auto endTime = std::chrono::high_resolution_clock::now();
	auto totalTime = endTime - startTime;

	printf("\t fizz : %d, buzz: %d, fizzbuzz: %d, duration %lld milliseconds\n", fizz, buzz, fizzbuzz, (totalTime / std::chrono::milliseconds(1)));

	return 0;
}
ColdFusion (7 lines)
<Cfloop from="1" to="100" index="i">
  <Cfif i mod 15 eq 0>FizzBuzz
  <Cfelseif i mod 5 eq 0>Fizz
  <Cfelseif i mod 3 eq 0>Buzz
  <Cfelse><Cfoutput>#i# </Cfoutput>
  </Cfif>
</Cfloop>
Clojure (1 lines)
(doseq [x (range 1 101)] (println x (str (when (zero? (mod x 3)) "fizz") (when (zero? (mod x 5)) "buzz"))))
COBOL (36 lines)
      * FIZZBUZZ.COB
      * cobc -x -g FIZZBUZZ.COB
      *
       IDENTIFICATION        DIVISION.
       PROGRAM-ID.           fizzbuzz.
       DATA                  DIVISION.
       WORKING-STORAGE       SECTION.
       01 CNT      PIC 9(03) VALUE 1.
       01 REM      PIC 9(03) VALUE 0.
       01 QUOTIENT PIC 9(03) VALUE 0.
       PROCEDURE             DIVISION.
      *
       PERFORM UNTIL CNT > 100
         DIVIDE 15 INTO CNT GIVING QUOTIENT REMAINDER REM
         IF REM = 0
           THEN
             DISPLAY "FizzBuzz " WITH NO ADVANCING
           ELSE
             DIVIDE 3 INTO CNT GIVING QUOTIENT REMAINDER REM
             IF REM = 0
               THEN
                 DISPLAY "Fizz " WITH NO ADVANCING
               ELSE
                 DIVIDE 5 INTO CNT GIVING QUOTIENT REMAINDER REM
                 IF REM = 0
                   THEN
                     DISPLAY "Buzz " WITH NO ADVANCING
                   ELSE
                     DISPLAY CNT " " WITH NO ADVANCING
                 END-IF
             END-IF
         END-IF
         ADD 1 TO CNT
       END-PERFORM
       DISPLAY ""
       STOP RUN.
CoffeeScript (9 lines)
for i in [1..100]
  if i % 15 is 0
    console.log "FizzBuzz"
  else if i % 3 is 0
    console.log "Fizz"
  else if i % 5 is 0
    console.log "Buzz"
  else
    console.log i
Common-Lisp (7 lines)
(defun fizzbuzz ()
  (loop for x from 1 to 100 do
    (princ (cond ((zerop (mod x 15)) "FizzBuzz")
                 ((zerop (mod x 3))  "Fizz")
                 ((zerop (mod x 5))  "Buzz")
                 (t                  x)))
    (terpri)))
C-sharp (33 lines)
class Program
{
    public void FizzBuzzGo()
    {
        Boolean Fizz = false;
        Boolean Buzz = false;
        for (int count = 1; count <= 100; count ++)
        {
            Fizz = count % 3 == 0;
            Buzz = count % 5 == 0;
            if (Fizz && Buzz)
            {
                Console.WriteLine("Fizz Buzz");
                listBox1.Items.Add("Fizz Buzz");
            }
            else if (Fizz)
            {
                Console.WriteLine("Fizz");
                listBox1.Items.Add("Fizz");
            }
            else if (Buzz)
            {
                Console.WriteLine("Buzz");
                listBox1.Items.Add("Buzz");
            }
            else
            {
                Console.WriteLine(count);
                listBox1.Items.Add(count);
            }
        }
    }
}
Crystal (11 lines)
1.upto(100) do |v|
  p fizz_buzz(v)
end

def fizz_buzz(value)
  word = ""
  word += "fizz" if value % 3 == 0
  word += "buzz" if value % 5 == 0
  word += value.to_s if word.empty?
  word
end
D (53 lines)
import std.stdio, std.algorithm, std.conv;

/// With if-else.
void fizzBuzz(in uint n) {
    foreach (immutable i; 1 .. n + 1)
        if (!(i % 15))
            "FizzBuzz".writeln;
        else if (!(i % 3))
            "Fizz".writeln;
        else if (!(i % 5))
            "Buzz".writeln;
        else
            i.writeln;
}

/// With switch case.
void fizzBuzzSwitch(in uint n) {
    foreach (immutable i; 1 .. n + 1)
        switch (i % 15) {
            case 0:
                "FizzBuzz".writeln;
                break;
            case 3, 6, 9, 12:
                "Fizz".writeln;
                break;
            case 5, 10:
                "Buzz".writeln;
                break;
            default:
                i.writeln;
        }
}

void fizzBuzzSwitch2(in uint n) {
    foreach (immutable i; 1 .. n + 1)
        (i % 15).predSwitch(
        0,       "FizzBuzz",
        3,       "Fizz",
        5,       "Buzz",
        6,       "Fizz",
        9,       "Fizz",
        10,      "Buzz",
        12,      "Fizz",
        /*else*/ i.text).writeln;
}

void main() {
    100.fizzBuzz;
    writeln;
    100.fizzBuzzSwitch;
    writeln;
    100.fizzBuzzSwitch2;
}
Dart (10 lines)
main() {
  for (int i = 1; i <= 100; i++) {
    List<String> out = [];
    if (i % 3 == 0)
      out.add("Fizz");
    if (i % 5 == 0)
      out.add("Buzz");
    print(out.length > 0 ? out.join("") : i);
  }
}
Delphi (21 lines)
program FizzBuzz;

{$APPTYPE CONSOLE}

uses SysUtils;

var
  i: Integer;
begin
  for i := 1 to 100 do
  begin
    if i mod 15 = 0 then
      Writeln('FizzBuzz')
    else if i mod 3 = 0 then
      Writeln('Fizz')
    else if i mod 5 = 0 then
      Writeln('Buzz')
    else
      Writeln(i);
  end;
end.
Elixir (8 lines)
Enum.each 1..100, fn x ->
  IO.puts(case { rem(x,3) == 0, rem(x,5) == 0 } do
    { true, true }   -> "FizzBuzz"
    { true, false }  -> "Fizz"
    { false, true }  -> "Buzz"
    { false, false } -> x
  end)
end
Elm (15 lines)
import Html exposing (text)
import List exposing (map)

main =
  [1..100] |> map getWordForNum |> text

getWordForNum num =
  if num % 15 == 0 then
    "FizzBuzz"
  else if num % 3 == 0 then
    "Fizz"
  else if num % 5 == 0 then
    "Buzz"
  else
    String.fromInt num
Emacs-Lisp (9 lines)
(defun fizzbuzz (n)
  (cond ((and (zerop (% n 5)) (zerop (% n 3))) "FizzBuzz")
	((zerop (% n 3)) "Fizz")
	((zerop (% n 5)) "Buzz")
	(t n)))

;; loop & print from 0 to 100
(dotimes (i 101)
  (message "%s" (fizzbuzz i)))
Erlang (8 lines)
-spec fizzbuzz() -> Result :: string().
fizzbuzz() ->
    F = fun(N) when N rem 15 == 0 -> "FizzBuzz";
           (N) when N rem 3 == 0  -> "Fizz";
           (N) when N rem 5 == 0  -> "Buzz";
           (N) -> integer_to_list(N)
        end,
    lists:flatten([[F(N)] ++ ["\n"] || N <- lists:seq(1,100)]).
Euphoria (33 lines)
include std/utils.e

function fb( atom n )
	sequence fb
	if remainder( n, 15 ) = 0 then
		fb = "FizzBuzz"
	elsif remainder( n, 5 ) = 0 then
		fb = "Fizz"
	elsif remainder( n, 3 ) = 0 then
		fb = "Buzz"
	else
		fb = sprintf( "%d", n )
	end if
	return fb
end function

function fb2( atom n )
	return iif( remainder(n, 15) = 0, "FizzBuzz",
		iif( remainder( n, 5 ) = 0, "Fizz",
		iif( remainder( n, 3) = 0, "Buzz", sprintf( "%d", n ) ) ) )
end function

for i = 1 to 30 do
	printf( 1, "%s ", { fb( i ) } )
end for

puts( 1, "\n" )

for i = 1 to 30 do
	printf( 1, "%s ", { fb2( i ) } )
end for

puts( 1, "\n" )
Fortran (11 lines)
program fizzbuzz_if
   integer :: i

   do i = 1, 100
      if     (mod(i,15) == 0) then; print *, 'FizzBuzz'
      else if (mod(i,3) == 0) then; print *, 'Fizz'
      else if (mod(i,5) == 0) then; print *, 'Buzz'
      else;                         print *, i
      end if
   end do
end program fizzbuzz_if
F-Sharp (9 lines)
let fizzbuzz n =
    match n%3 = 0, n%5 = 0 with
    | true, false -> "fizz"
    | false, true -> "buzz"
    | true, true  -> "fizzbuzz"
    | _ -> string n

let printFizzbuzz() =
    [1..100] |> List.iter (fizzbuzz >> printfn "%s")
Gleam (19 lines)
import gleam/int
import gleam/io
import gleam/iterator

pub fn main() {
  iterator.range(1, 101)
  |> iterator.map(to_fizzbuzz)
  |> iterator.map(io.println)
  |> iterator.run
}

fn to_fizzbuzz(n: Int) -> String {
  case n % 3, n % 5 {
    0, 0 -> "FizzBuzz"
    0, _ -> "Fizz"
    _, 0 -> "Buzz"
    _, _ -> int.to_string(n)
  }
}
Go (18 lines)
package main

import "fmt"

func main() {
    for i := 1; i <= 100; i++ {
        switch {
        case i%15==0:
            fmt.Println("FizzBuzz")
        case i%3==0:
            fmt.Println("Fizz")
        case i%5==0:
            fmt.Println("Buzz")
        default:
            fmt.Println(i)
        }
    }
}
Groovy (1 lines)
1.upto(100) { i -> println "${i % 3 ? '' : 'Fizz'}${i % 5 ? '' : 'Buzz'}" ?: i }
Haskell (11 lines)
fizzbuzz :: Int -> String
fizzbuzz x
  | f 15 = "FizzBuzz"
  | f 3 = "Fizz"
  | f 5 = "Buzz"
  | otherwise = show x
  where
    f = (0 ==) . rem x

main :: IO ()
main = mapM_ (putStrLn . fizzbuzz) [1 .. 100]
Java (15 lines)
public class FizzBuzz {
    public static void main(String[] args) {
        for (int number = 1; number <= 100; number++) {
            if (number % 15 == 0) {
                System.out.println("FizzBuzz");
            } else if (number % 3 == 0) {
                System.out.println("Fizz");
            } else if (number % 5 == 0) {
                System.out.println("Buzz");
            } else {
                System.out.println(number);
            }
        }
    }
}
JavaScript (9 lines)
var fizzBuzz = function () {
  var i, output;
  for (i = 1; i < 101; i += 1) {
    output = '';
    if (!(i % 3)) { output += 'Fizz'; }
    if (!(i % 5)) { output += 'Buzz'; }
    console.log(output || i);//empty string is false, so we short-circuit
  }
};
Jq (6 lines)
range(1;101)
  | if   . % 15 == 0 then "FizzBuzz"
    elif . % 5  == 0 then "Buzz"
    elif . % 3  == 0 then "Fizz"
    else .
    end
Julia (11 lines)
for i in 1:100
    if i % 15 == 0
        println("FizzBuzz")
    elseif i % 3 == 0
        println("Fizz")
    elseif i % 5 == 0
        println("Buzz")
    else
        println(i)
    end
end
Kotlin (12 lines)
fun fizzBuzz() {
    for (number in 1..100) {
        println(
            when {
                number % 15 == 0 -> "FizzBuzz"
                number % 3 == 0 -> "Fizz"
                number % 5 == 0 -> "Buzz"
                else -> number
            }
        )
    }
}
Lua (11 lines)
for i = 1, 100 do
	if i % 15 == 0 then
		print("FizzBuzz")
	elseif i % 3 == 0 then
		print("Fizz")
	elseif i % 5 == 0 then
		print("Buzz")
	else
		print(i)
	end
end
MIPS-Assembly (74 lines)
#################################
# Fizz Buzz                     #
# MIPS Assembly targetings MARS #
# By Keith Stellyes             #
# August 24, 2016               #
#################################

# $a0 left alone for printing
# $a1 stores our counter
# $a2 is 1 if not evenly divisible

.data
	fizz: .asciiz "Fizz\n"
	buzz: .asciiz "Buzz\n"
	fizzbuzz: .asciiz "FizzBuzz\n"
	newline: .asciiz "\n"

.text
loop:
	beq $a1,100,exit
	add $a1,$a1,1
	
	#test for counter mod 15 ("FIZZBUZZ")
	div $a2,$a1,15
	mfhi $a2
	bnez $a2,loop_not_fb #jump past the fizzbuzz print logic if NOT MOD 15
	
#### PRINT FIZZBUZZ: ####
	li $v0,4 #set syscall arg to PRINT_STRING
	la $a0,fizzbuzz #set the PRINT_STRING arg to fizzbuzz
	syscall #call PRINT_STRING
	j loop #return to start
#### END PRINT FIZZBUZZ ####
	
loop_not_fb:	
	div $a2,$a1,3 #divide $a1 (our counter) by 3 and store remainder in HI
	mfhi $a2 #retrieve remainder (result of MOD)
	bnez $a2, loop_not_f #jump past the fizz print logic if NOT MOD 3
	
#### PRINT FIZZ ####
	li $v0,4
	la $a0,fizz
	syscall
	j loop
#### END PRINT FIZZ ####

loop_not_f:
	div $a2,$a1,5
	mfhi $a2
	bnez $a2,loop_not_b

#### PRINT BUZZ ####
	li $v0,4
	la $a0,buzz
	syscall
	j loop
#### END PRINT BUZZ ####

loop_not_b:
	#### PRINT THE INTEGER ####
	li $v0,1 #set syscall arg to PRINT_INTEGER
	move $a0,$a1 #set PRINT_INTEGER arg to contents of $a1
	syscall #call PRINT_INTEGER
	
	### PRINT THE NEWLINE CHAR ###
	li $v0,4 #set syscall arg to PRINT_STRING
	la $a0,newline
	syscall
	
	j loop #return to beginning

exit:
	li $v0,10
	syscall
Nim (9 lines)
for i in 1..100:
  if i mod 15 == 0:
    echo("FizzBuzz")
  elif i mod 3 == 0:
    echo("Fizz")
  elif i mod 5 == 0:
    echo("Buzz")
  else:
    echo(i)
Objective-C (16 lines)
// FizzBuzz in Objective-C
#import <Foundation/Foundation.h>

int main(int argc, char* argv[]) {
	for (NSInteger i=1; I <= 101; i++) {
		if (i % 15 == 0) {
		    NSLog(@"FizzBuzz\n");
		} else if (i % 3 == 0) {
		    NSLog(@"Fizz\n");
		} else if (i % 5 == 0) {
		    NSLog(@"Buzz\n");
		} else {
		    NSLog(@"%li\n", i);
		}
	}
}
OCaml (9 lines)
let fizzbuzz i =
  match i mod 3, i mod 5 with
    0, 0 -> "FizzBuzz"
  | 0, _ -> "Fizz"
  | _, 0 -> "Buzz"
  | _    -> string_of_int i

let _ =
  for i = 1 to 100 do print_endline (fizzbuzz i) done
Perl (10 lines)
use strict;
use warnings;
use feature qw(say);

for my $i (1..100) {
    say $i % 15 == 0 ? "FizzBuzz"
      : $i %  3 == 0 ? "Fizz"
      : $i %  5 == 0 ? "Buzz"
      : $i;
}
Smalltalk (9 lines)
Integer extend [
    fizzbuzz [
        | fb |
        fb := '%<Fizz|>1%<Buzz|>2' % {
            self \\ 3 == 0.  self \\ 5 == 0 }.
        ^fb isEmpty ifTrue: [ self ] ifFalse: [ fb ]
    ]
]
1 to: 100 do: [ :i | i fizzbuzz displayNl ]
PHP (13 lines)
<?php
for ($i = 1; $i <= 100; $i++)
{
    if (!($i % 15))
        echo "FizzBuzz\n";
    else if (!($i % 3))
        echo "Fizz\n";
    else if (!($i % 5))
        echo "Buzz\n";
    else
        echo "$i\n";
}
?>
PL-SQL (15 lines)
begin
  for i in 1 .. 100
  loop
    case
    when mod(i, 15) = 0 then
      dbms_output.put_line('FizzBuzz');
    when mod(i, 5) = 0 then
      dbms_output.put_line('Buzz');
    when mod(i, 3) = 0 then
      dbms_output.put_line('Fizz');
    else
      dbms_output.put_line(i);
    end case;
  end loop;
end;
PowerShell (11 lines)
for ($i = 1; $i -le 100; $i++) {
    if ($i % 15 -eq 0) {
        "FizzBuzz"
    } elseif ($i % 5 -eq 0) {
        "Buzz"
    } elseif ($i % 3 -eq 0) {
        "Fizz"
    } else {
        $i
    }
}
Prolog (13 lines)
fizzbuzz :-
   forall(between(1, 100, X), print_item(X)).

print_item(X) :-
   (  X mod 15 =:= 0
   -> write('FizzBuzz')
   ;  X mod 3 =:= 0
   -> write('Fizz')
   ;  X mod 5 =:= 0
   -> write('Buzz')
   ;  write(X)
   ),
   nl.
Pyret (18 lines)
fun fizzbuzz(n :: NumPositive) -> String:
  doc: ```For positive input which is multiples of three return 'Fizz', for the multiples of five return 'Buzz'.
  For numbers which are multiples of both three and five return 'FizzBuzz'. Otherwise, return the number itself.```
  ask:
    | num-modulo(n, 15) == 0 then: "FizzBuzz"
    | num-modulo(n, 3) == 0 then: "Fizz"
    | num-modulo(n, 5) == 0 then: "Buzz"
    | otherwise: num-to-string(n)
  end
where:
  fizzbuzz(1) is "1"
  fizzbuzz(101) is "101"
  fizzbuzz(45) is "FizzBuzz"
  fizzbuzz(33) is "Fizz"
  fizzbuzz(25) is "Buzz"
end

range(1, 101).map(fizzbuzz).each(print)
Python (9 lines)
for i in range(1, 101):
    if i % 15 == 0:
        print "FizzBuzz"
    elif i % 3 == 0:
        print "Fizz"
    elif i % 5 == 0:
        print "Buzz"
    else:
        print i
R (5 lines)
xx <- x <- 1:100
xx[x %% 3 == 0] <- "Fizz"
xx[x %% 5 == 0] <- "Buzz"
xx[x %% 15 == 0] <- "FizzBuzz"
xx
Racket (9 lines)
#lang racket

(for ([n (in-range 1 101)])
  (displayln
   (match (gcd n 15)
     [15 "fizzbuzz"]
     [3 "fizz"]
     [5 "buzz"]
     [_ n])))
Raku (6 lines)
for 1 .. 100 {
    when $_ %% (3 & 5) { say 'FizzBuzz'; }
    when $_ %% 3       { say 'Fizz'; }
    when $_ %% 5       { say 'Buzz'; }
    default            { .say; }
}
Red (10 lines)
Red [Title: "FizzBuzz"]

repeat i 100 [
    print case [
        i % 15 = 0 ["FizzBuzz"]
        i % 5 = 0 ["Buzz"]
        i % 3 = 0 ["Fizz"]
        true [i]
    ]
]
Ruby (6 lines)
1.upto(100) do |n|
  print "Fizz" if a = (n % 3).zero?
  print "Buzz" if b = (n % 5).zero?
  print n unless (a || b)
  puts
end
Rust (10 lines)
fn main() {
    for i in 1..=100 {
        match (i % 3, i % 5) {
            (0, 0) => println!("fizzbuzz"),
            (0, _) => println!("fizz"),
            (_, 0) => println!("buzz"),
            (_, _) => println!("{}", i),
        }
    }
}
Scala (10 lines)
object FizzBuzz extends App {
  1 to 100 foreach { n =>
    println((n % 3, n % 5) match {
      case (0, 0) => "FizzBuzz"
      case (0, _) => "Fizz"
      case (_, 0) => "Buzz"
      case _ => n
    })
  }
}
Scheme (8 lines)
(do ((i 1 (+ i 1)))
    ((> i 100))
    (display
      (cond ((= 0 (modulo i 15)) "FizzBuzz")
            ((= 0 (modulo i 3))  "Fizz")
            ((= 0 (modulo i 5))  "Buzz")
            (else                i)))
    (newline))
SQL (8 lines)
SELECT CASE
    WHEN MOD(level,15)=0 THEN 'FizzBuzz'
    WHEN MOD(level,3)=0 THEN 'Fizz'
    WHEN MOD(level,5)=0 THEN 'Buzz'
    ELSE TO_CHAR(level)
    END FizzBuzz
    FROM dual
    CONNECT BY LEVEL <= 100;
Standard-ML (14 lines)
local
  fun fbstr i =
      case (i mod 3 = 0, i mod 5 = 0) of
          (true , true ) => "FizzBuzz"
        | (true , false) => "Fizz"
        | (false, true ) => "Buzz"
        | (false, false) => Int.toString i

  fun fizzbuzz' (n, j) =
      if n = j then () else (print (fbstr j ^ "\n"); fizzbuzz' (n, j+1))
in
  fun fizzbuzz n = fizzbuzz' (n, 1)
  val _ = fizzbuzz 100
end
Swift (12 lines)
for i in 1...100 {
    switch (i % 3, i % 5) {
    case (0, 0):
        print("FizzBuzz")
    case (0, _):
        print("Fizz")
    case (_, 0):
        print("Buzz")
    default:
        print(i)
    }
}
Tcl (9 lines)
proc fizzbuzz {n {m1 3} {m2 5}} {
    for {set i 1} {$i <= $n} {incr i} {
        set ans ""
        if {$i % $m1 == 0} {append ans Fizz}
        if {$i % $m2 == 0} {append ans Buzz}
        puts [expr {$ans eq "" ? $i : $ans}]
    }
}
fizzbuzz 100
V (9 lines)
[fizzbuzz
    1 [>=] [
     [[15 % zero?] ['fizzbuzz' puts]
      [5 % zero?]  ['buzz' puts]
      [3 % zero?]  ['fizz' puts]
      [true] [dup puts]
    ] when succ
  ] while].
 |100 fizzbuzz
Vim-Script (11 lines)
for i in range(1, 100)
    if i % 15 == 0
        echo "FizzBuzz"
    elseif i % 5 == 0
        echo "Buzz"
    elseif i % 3 == 0
        echo "Fizz"
    else
        echo i
    endif
endfor
Wren (11 lines)
for (i in 1..100) {
    if (i % 15 == 0) {
        System.print("FizzBuzz")
    } else if (i % 3 == 0) {
        System.print("Fizz")
    } else if (i % 5 == 0) {
        System.print("Buzz")
    } else {
        System.print(i)
    }
}
Zig (15 lines)
const print = @import("std").debug.print;
pub fn main() void {
    var i: usize = 1;
    while (i <= 100) : (i += 1) {
        if (i % 3 == 0 and i % 5 == 0) {
            print("FizzBuzz\n", .{});
        } else if (i % 3 == 0) {
            print("Fizz\n", .{});
        } else if (i % 5 == 0) {
            print("Buzz\n", .{});
        } else {
            print("{}\n", .{i});
        }
    }
}

About

About the ys-vs-rc Project

YAMLScript is a relatively new programming language and this project is intended to show how things are done with it compared to some other programming languages.

When comparing these programs, keep in mind that they were all written by different people and they are not necessarily exactly equivalent.

For example, most of the YAMLScript programs are written to be runnable with:

$ ys task-name.ys

which prints the intended results.

This is not necessarily the case for the solutions in other languages. Many solutions just show the functions necessary to complete the task.

Also the line counts are not meant ot imply any superiority of a solution.

Contributing

A great way to contribute to YAMLScript is to add more YAMLScript task solutions to Rosetta Code.

You can use this program to compare your solutions with others.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment