Skip to content

Instantly share code, notes, and snippets.

bstCount :: (Int -> Integer) -> Int -> Integer
bstCount rec n
| n <= 1 = 1
| otherwise = sum [rec i * rec (n-1-i) | i <- [0..n-1]]
fizzBuzz :: [(Int, String)] -> Int -> String
fizzBuzz rules i =
let r = concatMap (\(n,s) -> if mod i n == 0 then s else "") rules
in if r == "" then show i else r
{-# LANGUAGE OverloadedStrings #-}
import Data.Monoid((<>))
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.Builder as B
-- The API of the fizz buzz
type Rule = B.Builder -> Int -> B.Builder
newtype SortedList a = SortedList { unSortedList :: [a] }
instance (Ord a) => Monoid (SortedList a) where
mempty = SortedList []
mappend (SortedList a) (SortedList b) = SortedList $ merge a b
foldMergeSort :: (Ord a) => [a] -> [a]
foldMergeSort = unSortedList . foldMonoidTree . map (\x -> SortedList [x])
merge :: (Ord a) => [a] -> [a] -> [a]
merge xs [] = xs
merge [] ys = ys
merge l@(x:xs) r@(y:ys)
| y < x = y : merge l ys -- Keeps it stable
| otherwise = x : merge xs r
template<typename Iterator, typename Value, typename BinaryOp>
Value add_to_counter(Iterator first, Iterator last,
Value carry, Value const &zero,
BinaryOp op)
{
assert(carry != zero);
for (; first != last; ++first) {
if (*first == zero) {
*first = carry;
return zero;
template<typename Iterator, typename Value, typename Accumulator>
Value accumulate_iter(Iterator first, Iterator last,
Value val, Accumulator fct)
{
for (; first != last; ++first)
val = fct(val, first);
return val;
};
template<typename Iterator>
struct merger
{
using Value = typename std::iterator_traits<Iterator>::value_type;
using SortedRange = std::pair<Iterator, Iterator>;
SortedRange operator()(SortedRange const &lhs, SortedRange const &rhs) const {
assert(lhs.second == rhs.first);
std::vector<Value> tmp(lhs.first, lhs.second); //Copy the left range
std::merge(
template<typename ForwardIterator>
void stable_sort_forward(ForwardIterator first, ForwardIterator last)
{
using Range = std::pair<ForwardIterator, ForwardIterator>;
using Counter = binary_counter<merger<ForwardIterator>, Range>;
Counter c { merger<ForwardIterator>{}, { last, last } };
accumulate_iter(first, last, &c,
[](auto c, auto it) {
c->add({it, std::next(it)});
template<typename ForwardIterator>
void stable_sort_forward(ForwardIterator first, ForwardIterator last)
{
using Range = std::pair<ForwardIterator, ForwardIterator>;
using Counter = binary_counter<merger<ForwardIterator>, Range>;
Counter c { merger<ForwardIterator>{}, { last, last } };
for (; first != last; ++first) {
c.add(std::make_pair(first, std::next(first)));
}