Last active
January 2, 2021 10:30
-
-
Save MartinPavlik/0e0b1c7f77a72294075b65450674b04f to your computer and use it in GitHub Desktop.
FizzBuzz katas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns clojure.examples.hello | |
(:gen-class)) | |
;; how to execute a function? (fn argument1 argument2 ...) | |
;; this is how a function is defined | |
(defn isMod0 [i n] | |
(= 0 (mod i n))) | |
(defn fizzBuzz | |
;; fizzBuzz defined for 0 arguments | |
([] | |
(fizzBuzz 1 101)) | |
;; fizzBuzz defined for 1 argument | |
([i] | |
(cond | |
(isMod0 i 15) "FizzBuzz" | |
(isMod0 i 5) "Buzz" | |
(isMod0 i 3) "Fizz" | |
:else (str i))) | |
;; overloaded fizzBuzz that takes 2 args | |
([start end] | |
;; take the function str and apply it to the list | |
(apply str | |
;; put "\n" between all items in the list, so returns something like ("1" "\n" "2" "\n" "3") | |
(interpose "\n" | |
;; lift the function fizzBuzz to operate on lists | |
(map fizzBuzz | |
;; generate a list from start to end | |
(range start end)))))) | |
;; a problem I have with clojure is that the interpreter gives errors that are kinda hard to understand | |
(println (fizzBuzz)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fizzBuzz:: (Show a, Integral a) => a -> String | |
fizzBuzz i | mod i (3 * 5) == 0 = "FizzBuzz" | |
fizzBuzz i | mod i 3 == 0 = "Fizz" | |
fizzBuzz i | mod i 5 == 0 = "Buzz" | |
fizzBuzz i = show i | |
main = putStr $ unlines $ (map fizzBuzz [1..100]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* lists are the same as in haskell, so recursive data structure */ | |
let rec range = (start: int, end_: int) => | |
if (start >= end_) { | |
[]; | |
} else { | |
[start, ...range(start + 1, end_)]; | |
}; | |
let fizzBuzzOne = (i) => | |
/* pattern matching */ | |
switch (i mod 3, i mod 5) { | |
| (0, 0) => "FizzBuzz" | |
| (0, _) => "Fizz" | |
| (_, 0) => "Buzz" | |
| _ => string_of_int(i) | |
}; | |
let fizzBuzz = () => range(1, 101) |> List.map(fizzBuzzOne) |> String.concat("\n") | |
Js.log(fizzBuzz()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment