Skip to content

Instantly share code, notes, and snippets.

@phagenlocher
Created January 15, 2020 12:49
Show Gist options
  • Select an option

  • Save phagenlocher/b2823a737bf1c15f5ab255697a6ccdaa to your computer and use it in GitHub Desktop.

Select an option

Save phagenlocher/b2823a737bf1c15f5ab255697a6ccdaa to your computer and use it in GitHub Desktop.
rev :: [a] -> [a]
rev = foldl (\acc x -> x : acc) []
--rev = foldl (flip (:)) []
prefixes :: [a] -> [[a]]
prefixes = foldr (\x acc -> [x] : (map ((:) x) acc)) []
lagrange :: [(Float, Float)] -> Float -> Float
lagrange xs x = foldl (\acc (xj,y) -> acc + (y * l xj)) 0 xs
where
l xj = foldl (
\acc (xk,_) ->
if xj==xk then
acc
else
acc * ((x-xk)/(xj-xk))
) 1 xs
data Trie a = Leaf a | Node a [Trie a]
foldtrie :: (b -> a -> b) -> b -> Trie a -> b
foldtrie f acc (Leaf x) = f acc x
foldtrie f acc (Node x xs) = foldl f' (f acc x) xs
where
f' acc t = foldtrie f acc t
t = Node 'c' [(Node 'a' [Leaf 'r', Leaf 't']),(Node 'o' [Node 'o' [Leaf 'l']])]
@phagenlocher
Copy link
Author

The output is dependent on the function that is used with foldtrie. It is equivalent with foldl for lists where the leftmost leafs of the trie are the first ones that the function is used on. So if we want to create a string representing the leafs of the tree (going from left to right) we have to append the elements to the accumulator: foldtrie (\acc x -> acc ++ [x]) "" t

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment