Skip to content

Instantly share code, notes, and snippets.

@ntreu14
ntreu14 / map-filter.fsx
Last active October 20, 2017 19:16
Different ways to implement a filter then map
let isEven num = num % 2 = 0
let square num = num * num
let printResults = List.iter <| printfn "%d"
// Filter then map
[1..5]
|> List.filter isEven
|> List.map square
|> printResults
@ntreu14
ntreu14 / fold-reduce.java
Last active January 18, 2018 22:47
Implementing fold and reduce in Java
import java.util.function.BiFunction;
import java.util.List;
import java.util.Arrays;
public class FunctionsExample {
public static void main(String[] args) {
String[] strs = {"Example", "Strings", "To", "Join"};
List<String> strsList = Arrays.asList(strs);
@ntreu14
ntreu14 / fold-reduce.fsx
Last active January 18, 2018 22:50
Implementations of fold and reduce functions in F#
let rec fold f state list =
match list with
| [] -> state
| head::rest -> fold f (f state head) rest
let reduce f list =
match list with
| [] -> invalidArg "list" "Cannot pass an empty list"
| head::rest -> fold f head rest
@ntreu14
ntreu14 / ConsList.fs
Last active December 18, 2018 22:12
Cons list in F#
namespace ConsList
module List =
type 'a List =
| Nil
| Cons of ('a * 'a List)
let private asCons v = Cons (v, Nil)
@ntreu14
ntreu14 / CollectLeaves.fsx
Created January 11, 2019 19:31
Returns leaf nodes from a tree where the elements return true for a given predicate
type 'a Node = Group of 'a Node list | Leaf of 'a
let tree = Group [ Group [Leaf 1; Leaf 2; Leaf 3]; Group [Leaf 6]; Leaf 9; Leaf 10 ]
let isEven n = n % 2 = 0
let flip f a b = f b a
let (>>=) = flip List.collect
let rec collectLeavesBy predicate = function
| Group xs -> xs >>= (collectLeavesBy predicate)
open System
open System.Net
open System.Threading
[<EntryPoint>]
let main _ =
let url = "http://www.google.com"
let (>>=) (asyncBlock: Async<'a>) (f: 'a -> Async<'b>) =
async {
@ntreu14
ntreu14 / Peano.fsx
Last active June 13, 2019 14:20
Solution to CodeWars peano numbers kata
type Peano =
| Zero
| Succ of Peano
// Comapre
let rec cmp x y =
match x, y with
| Zero, Zero -> 0
| Zero, Succ _ -> -1
| Succ _, Zero -> 1
@ntreu14
ntreu14 / FindTreeHeight.fs
Created August 8, 2019 20:57
Find height of a binary tree
type 'a Node =
| Leaf of 'a
| Group of ('a Node * 'a Node)
let findTreeHeight tree =
let rec aux tree counter =
match tree with
| Leaf _ -> counter
| Group (left, right) ->
let leftTreeHeight = aux left (counter + 1)
module AoCDay8Part1 where
data Node = Node [Node] [Int]
solve :: [Int] -> ([Int], Node)
solve (nChild:nEntries:rest) =
(remainingToBeParsed, Node children entries)
where
remainingToBeParsed = drop nEntries restChildren
entries = take nEntries restChildren
module AoCDay8Part2 where
data Node = Node [Node] [Int]
solve :: [Int] -> ([Int], Node)
solve (nChild:nEntries:rest) =
(remainingToBeParsed, Node children entries)
where
remainingToBeParsed = drop nEntries restChildren
entries = take nEntries restChildren