Skip to content

Instantly share code, notes, and snippets.

@SevanBadal
Last active April 19, 2023 19:39
Show Gist options
  • Save SevanBadal/e443fb7ee88969fee8ccb961be4e1d8a to your computer and use it in GitHub Desktop.
Save SevanBadal/e443fb7ee88969fee8ccb961be4e1d8a to your computer and use it in GitHub Desktop.
Haskelliday: A Functor-Applicative-Monad Break from Class. I suggest loading this file into GHCI and exploring the main function and MyTree data type before proceeding to the questions.
import System.Random (StdGen, randomR, split, newStdGen)
-- main to help debug your Functor, Applicative and Monad instances
-- feel free to edit main!
main :: IO ()
main = do
treeOne <- generateRandomTree 10 -- tree of ten random nodes
-- you will end of needing to construct a tree of expressions of some type (a -> a) for the applicative
-- you can construct that tree manually via value constructors or by creating a new generateTree function
print treeOne
-- helper function to generate a new tree given a standard gen
-- don't edit this function!
generateTree :: Int -> StdGen -> (MyTree Int, StdGen)
generateTree 0 g = (Nil, g)
generateTree n g = (Node value leftTree rightTree, g3)
where
(value, g1) = randomR (1, 100) g
(g2, g3) = split g1
n' = (n - 1) `div` 2
(leftTree, _) = generateTree n' g2
(rightTree, _) = generateTree (n - 1 - n') g3
-- helper function to build and return a tree with random values
-- don't edit this function!
generateRandomTree :: Int -> IO (MyTree Int)
generateRandomTree n = do
g <- newStdGen
let (tree, nextGen) = generateTree n g
return tree
-- Implement a Functor, Applicative, and Monad instance for the following custom data type:
data MyTree a = Nil | Node a (MyTree a) (MyTree a) deriving Show
-- Question 1 : Functor
-- In the Functor instance for the MyTree data type,
-- fmap applies a function to each value in the tree while
-- preserving its structure. The fmap function recursively traverses
-- the tree and applies the given function to every value it encounters in the tree.
-- Question 2 : Applicative
-- In the Applicative instance for the MyTree data type,
-- the <*> operator combines two trees by applying a tree of
-- functions to a tree of values in a pairwise manner.
-- It recursively traverses both trees and applies each function
-- from the first tree to the corresponding value in the second tree,
-- creating a new tree with the results.
-- Question 3 : Monad
-- In the Monad instance for the MyTree data type,
-- the bind operation (implemented using the >>= operator) is used
-- to apply a function that returns a MyTree to each value in the input tree,
-- then merges the resulting trees while preserving the overall structure.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment