3 ms·
I didn't make it past the fizzbuzz example. But I wouldn't call the solution with cycle all that clever. Here's a better one: https://themonadreader.files.wordp
by ezyang 10y ago
I didn't make it past the fizzbuzz example. But I wouldn't call the solution with cycle all that clever. Here's a better one: https://themonadreader.files.wordpress.com/2014/04/fizzbuzz.pdf https://themonadreader.files.wordpress.com/2014/04/fizzbuzz....
the punchline reproduced below:
fizzbuzz' :: Int -> String
fizzbuzz' n = (test 3 "fizz" . test 5 "buzz") id (show n)
where
test d s x | n `mod` d == 0 = const (s ++ x "")
| otherwise = x
fizzbuzz :: [String]
fizzbuzz = map fizzbuzz' [1..]
The article is very interesting and worth a read. In particular, this implementation doesn't come out of "thin air": it's been golfed from an implementation that defines a simple domain specific language to solve FizzBuzz. And if you understand your problem well enough, DSLs are an extreme force multiplier.
- squeaky-clean 10y agoFeature request: Client should be able to specify either 3, or 1023 for the number needed to print "fizz." Feature request: Client should be able to optionally request "Lizard" as another string whenever the number is a multiple of 13. That's what the article is referring to. Your function may be more clever, but it's more specific, works in only exactly the requested cases and is harder to change.
- mmierz 10y agofizzbuzz' :: Bool -> Bool -> Int -> String fizzbuzz' big doLiz n = (fizz . test 5 "buzz" . lizz) id (show n) where test d s x | n `mod` d == 0 = const (s ++ x "") | otherwise = x fizz = if big then (test 1023 "fizz") else (test 3 "fizz") lizz = if doLiz then (test 13 "Lizard") else id fizzbuzz :: Bool -> Bool -> [String] fizzbuzz big doLiz = map (fizzbuzz' big doLiz) [1..]
- tromp 10y agofizzbuzz' n = (test 1023 "fizz" . test 5 "buzz" . test 13 "Lizard") id (show n) easy as pie...