Skip to content

Instantly share code, notes, and snippets.

@abhin4v
abhin4v / astar.hs
Last active November 24, 2022 06:36
A* (A star) search in haskell
import qualified Data.PQueue.Prio.Min as PQ
import qualified Data.HashSet as Set
import qualified Data.HashMap.Strict as Map
import Data.Hashable (Hashable)
import Data.List (foldl')
import Data.Maybe (fromJust)
astarSearch :: (Eq a, Hashable a) => a -> (a -> Bool) -> (a -> [(a, Int)]) -> (a -> Int) -> Maybe (Int, [a])
astarSearch startNode isGoalNode nextNodeFn heuristic =
astar (PQ.singleton (heuristic startNode) (startNode, 0))
@animatedlew
animatedlew / len.hs
Last active April 16, 2024 14:09
Here are two ways to implement Haskell's length function. One way is to map all the elements to 1, then sum them all up. Another way is to add up each head as you recursively call len' with the tail. The result will be the length of the list.
-- Maps each element to a 1, then sums up all the elements
len :: [a] -> Integer
len = sum . map (\_ -> 1)
-- Adds up all the heads (recursively) until the list is empty
len' :: [a] -> Integer
len' [] = 0
len' (_:xs) = 1 + len' xs
-- Extract into a fold using this technique: [ [] := v, (:) := f ]