Skip to content

Instantly share code, notes, and snippets.

View rexcfnghk's full-sized avatar

Rex Ng rexcfnghk

  • Hong Kong
  • 09:18 (UTC +08:00)
View GitHub Profile
isLeapYear :: Int -> Bool
isLeapYear year =
if year `mod` 4 == 0
then
if year `mod` 100 == 0
then
if year `mod` 400 == 0
then True
else False
else True
atMay :: [a] -> Int -> Maybe a
[] `atMay` _ = None
[x] `atMay` 0 = Just x
(_:xs) `atMay` i = xs `atMay` (i - 1)
(!!) :: [a] -> Int -> a
[] !! _ = undefined
[x] !! 0 = x
(_:xs) !! i = xs !! (i - 1)
add :: a -> [a] -> [a]
add x xs = x : xs
-- it is more common to write as
-- add = (:)
remove :: (Eq a) => a -> [a] -> [a]
remove _ [] = []
remove t (x:xs) = if t == x then remove t xs else remove t (x:xs)
-- you can also write it as a fold
-- remove t = foldr (\x xs -> if x == t then xs else x:xs) []
mySum :: [Int] -> Int
mySum [] = 0
mySum (x:xs) = x + mySum xs
-– Empty list
[]
–- We use the cons operator (:) to combine the element 3 (an integer)
-- and an empty list (which can take on the type of integer list)
3 : []
-- The cons operator is right-associative. (3 : []) is also of type integer
-- list, we use the cons operator again to add the element 2 in front of it
2 : (3 : [])
-- The cons operator is right-associative. (2 : 3 : []) is also of type integer
-- list, we use the cons operator again to add the element 1 in front of it
data [] a = [] | a : [a]
const list = [];
list.push(1);
list.push(2);
list.push(3);
var list = new List<int> { 1, 2, 3 };
// Syntactic sugar of
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
join :: Monad m => m (m a) -> m a