gonzaw308
BAN USERimport Data.Monoid
import Control.Monad
-- Generic fizzbuzzer, for any monoid, for any list of possible fizzers or
-- buzzers, and for any function that
-- transforms the integer to a monadic value
fizzbuzzer :: Monoid a => [(Int,a)] -> (Int -> a ) -> Int -> a
fizzbuzzer printers trans n = app id (trans n)
where
app = appEndo . mconcat . fmap Endo . fmap test $ printers
test (val,str) f
| n `mod` val == 0 = const (str <> f mempty)
| otherwise = f
-- Specific fizzbuzz, takes a number and returns either that number as a
-- string, "Fizz", "Buzz" or "FizzBuzz"
fizzbuzz :: Int -> String
fizzbuzz = fizzbuzzer [(3,"Fizz"),(5,"Buzz")] show
-- IO action to get the N and print all fizzbuzzes up until that N
ioFizzBuzz n = forM_ [1 .. n] $ putStrLn . fizzbuzz
-- Gets number from STDIN and calls the IO FizzBuzz action
main = getLine >>= (ioFizzBuzz . read)
In Haskell:
getSubLists :: Int -> [Int] -> ([[Int]],[Int])
getSubLists n xs
| (length xs) < n = ([],xs)
| otherwise = let (res,rmd) = getSubLists n (drop n xs)
in
((take n xs):res,rmd)
reverseList :: Int -> [Int] -> [Int]
reverseList n xs =
let (sub,rmd) = getSubLists n xs
reversed = map reverse sub
in
(concat reversed) ++ rmd
Found a simpler way in 3 lines of Haskell code:
Example use:
Type signatures:
- gonzaw308 December 27, 2014