Difference between revisions of "Fizzbuzzing"

From The fun Wiki
Jump to navigation Jump to search
(Created page with "'''This article is a stub, and is currently a work in progress''' [https://en.wikipedia.org/wiki/Fizz_buzz FizzBuzz] is a common toy program for screening candidates on inte...")
 
 
(One intermediate revision by the same user not shown)
Line 12: Line 12:
 
== The ''imperative'' approach ==
 
== The ''imperative'' approach ==
  
From [https://rosettacode.org/wiki/FizzBuzz#Haskell],  
+
From the example in [https://rosettacode.org/wiki/FizzBuzz#Haskell Rosetta Code],  
 
   fizzbuzz x =  
 
   fizzbuzz x =  
 
     (\f ->  (f 15) "FizzBuzz"  
 
     (\f ->  (f 15) "FizzBuzz"  
Line 25: Line 25:
 
   get a b = a (show b) (\h t -> a);
 
   get a b = a (show b) (\h t -> a);
 
   fbz = zipWith (++) fizz buzz;
 
   fbz = zipWith (++) fizz buzz;
   fizz = <<"Fizz">> -- a Wheel;
+
   fizz = <|"Fizz"|> -- a Wheel;
   buzz = <<"Buzz">> -- another Wheel;
+
   buzz = <|"Buzz"|> -- another Wheel;
 
    
 
    
 
   main = print (fizzbuzz 100);
 
   main = print (fizzbuzz 100);

Latest revision as of 07:54, 21 July 2022

This article is a stub, and is currently a work in progress


FizzBuzz is a common toy program for screening candidates on interviews to programming jobs. On imperative languages it usually involves a simple loop and some conditional statements, using integer division (/) and mod (%) operations. With a functional programming language like Haskell, we are not restricted to this format, and can employ lazy data structures that do not require expensive division and mod operations.

In this pearl we will compare both imperative and lazy styles when targeting the fun ISA.

The problem

Write a program that prints the integers from 1 to n, but print Fizz for multiples of 3, print Buzz for multiples of 5, and print FizzBuzz for multiples of both 3 and 5.

The imperative approach

From the example in Rosetta Code,

 fizzbuzz x = 
   (\f ->  (f 15) "FizzBuzz" 
           ((f 3) "Fizz"
           ((f 5) "Buzz"
             (show x))))  (compose (== 0) (% x));      

 main = print (map fizzbuzz (range 1 100));

The lazy approach

 fizzbuzz n = take n (zipWith get fbz (from 1));  
 get a b = a (show b) (\h t -> a);
 fbz = zipWith (++) fizz buzz;
 fizz = <|"Fizz"|> -- a Wheel;
 buzz = <|"Buzz"|> -- another Wheel;
 
 main = print (fizzbuzz 100);