Created
January 2, 2019 15:57
-
-
Save DonaldKellett/7d3c0b4563474c87a66cbe478d1abb35 to your computer and use it in GitHub Desktop.
PureScript by Example - 6.7 Instance Dependencies - Exercise 1-6 Solutions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module InstanceDependencies where | |
import Prelude | |
import Data.Array | |
import Data.Foldable | |
-- Boilerplate for Exercises 1-3, 5 | |
data NonEmpty a = NonEmpty a (Array a) | |
-- For easier debugging | |
instance showNonEmpty :: Show a => Show (NonEmpty a) where | |
show (NonEmpty x xs) = show (x : xs) | |
-- Exercise 1 | |
instance eqNonEmpty :: Eq a => Eq (NonEmpty a) where | |
eq (NonEmpty x xs) (NonEmpty y ys) = x == y && xs == ys | |
-- Exercise 2 | |
instance semigroupNonEmpty :: Semigroup (NonEmpty a) where | |
append (NonEmpty x xs) (NonEmpty y ys) = NonEmpty x (snoc xs y <> ys) | |
-- Exercise 3 | |
instance functorNonEmpty :: Functor NonEmpty where | |
map f (NonEmpty x xs) = NonEmpty (f x) (map f xs) | |
-- Boilerplate code for Exercise 4 | |
data Extended a = Finite a | Infinite | |
-- Exercise 4 | |
instance eqExtended :: Eq a => Eq (Extended a) where | |
eq Infinite Infinite = true | |
eq Infinite _ = false | |
eq _ Infinite = false | |
eq (Finite x) (Finite y) = x == y | |
instance ordExtended :: Ord a => Ord (Extended a) where | |
compare Infinite Infinite = EQ | |
compare Infinite _ = GT | |
compare _ Infinite = LT | |
compare (Finite x) (Finite y) = compare x y | |
-- Exercise 5 | |
instance foldableNonEmpty :: Foldable NonEmpty where | |
foldr f seed (NonEmpty x xs) = f x (foldr f seed xs) | |
foldl f seed (NonEmpty x xs) = foldl f (f seed x) xs | |
foldMap f (NonEmpty x xs) = f x <> foldMap f xs | |
-- Boilerplate for Exercise 6 | |
data OneMore f a = OneMore a (f a) | |
-- Exercise 6 | |
instance foldableOneMore :: Foldable f => Foldable (OneMore f) where | |
foldr f seed (OneMore x xs) = f x (foldr f seed xs) | |
foldl f seed (OneMore x xs) = foldl f (f seed x) xs | |
foldMap f (OneMore x xs) = f x <> foldMap f xs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment