Skip to content

Instantly share code, notes, and snippets.

View rexcfnghk's full-sized avatar

Rex Ng rexcfnghk

View GitHub Profile
class Category y where
id :: y a a -- identity for composition.
(.) :: y b c -> y a b -> y a c -- associative composition.
instance Functor [] where
fmap _ [] = []
fmap f (x::xs) = f x :: fmap f xs
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just x) = Just (f x)
instance Functor (Either a) where
fmap _ x@(Left _) = x
public static List<int> Foo()
{
var list = new[] { 1, 2, 3, 4, 5 };
return list.Select(x => x).ToList();
}
import Data.Foldable
secondLargest :: (Ord a, Foldable t) => t a -> Maybe a
secondLargest = snd . foldl' secondLargest' (Nothing, Nothing) where
secondLargest' (Nothing, Nothing) x = (Just x, Just x)
secondLargest' (Just largest, Just second) x
| x > largest = (Just x, Just largest)
| x > second = (Just largest, Just x)
| otherwise = (Just largest, Just second)
secondLargest' tuple _ = tuple
snd :: (a, b) -> b
snd (_, x) = x
import Data.Foldable
secondLargest :: (Num a, Ord a, Foldable t) => t a -> a
secondLargest xs = snd . foldl' secondLargest' (0, 0) xs where
secondLargest' (largest, second) x
| x > largest = (x, largest)
| x > second = (largest, x)
| otherwise = (largest, second)
(.) :: (b -> c) -> (a -> b) -> a -> c
f . g = \x -> f (g x)
public static class Math
{
public static T SecondLargest<T>(IEnumerable<T> inputs) where T : IComparable<T>
{
// Null checks skipped for brevity
var (largest, second) = (default(T), default(T));
foreach (var input in inputs)
{
if (input.CompareTo(largest) > 0)
{
@rexcfnghk
rexcfnghk / second-largest.hs
Last active September 22, 2021 03:47
Find the second largest Num in a Foldable
import Data.Foldable
secondLargest :: (Num a, Ord a, Foldable t) => t a -> a
secondLargest = snd . foldl' secondLargest' (0, 0) where
secondLargest' (largest, second) x
| x > largest = (x, largest)
| x > second = (largest, x)
| otherwise = (largest, second)
isLeapYear :: Int -> Bool
isLeapYear year
| isDivisibleBy 400 = True
| isDivisibleBy 100 = False
| isDivisibleBy 4 = True
| otherwise = False
where isDivisibleBy divisor = year `mod` divisor == 0