Skip to content

Instantly share code, notes, and snippets.

@DonaldKellett
Created January 3, 2019 09:03
Show Gist options
  • Save DonaldKellett/db88c3ab386fb1132288b7b90550b3e0 to your computer and use it in GitHub Desktop.
Save DonaldKellett/db88c3ab386fb1132288b7b90550b3e0 to your computer and use it in GitHub Desktop.
PureScript by Example - 6.11 Superclasses - Exercise 1-4 Solutions
module Superclasses where
import Prelude
import Data.Array
import Data.Foldable
import Data.Maybe
-- Exercise 1
maxOf :: Partial => Array Int -> Int
maxOf = fromJust <<< maximum
-- Boilerplate for Exercises 2-3
class Monoid m <= Action m a where
act :: m -> a -> a
newtype Multiply = Multiply Int
instance semigroupMultiply :: Semigroup Multiply where
append (Multiply n) (Multiply m) = Multiply (n * m)
instance monoidMultiply :: Monoid Multiply where
mempty = Multiply 1
-- Exercise 2
instance repeatAction :: Action Multiply String where
act (Multiply 0) _ = ""
act (Multiply n) s = s <> act (Multiply (n - 1)) s
-- Exercise 3
instance actionOnArrays :: Action m a => Action m (Array a) where
act = map <<< act
-- Boilerplate for Exercise 4
newtype Self m = Self m
-- Exercise 4
instance monoidActsOnSelf :: Monoid m => Action m (Self m) where
act m (Self m') = Self (m <> m')
-- For debugging purposes
instance showMultiply :: Show Multiply where
show (Multiply n) = "Multiply (" <> show n <> ")"
instance showSelf :: Show a => Show (Self a) where
show (Self x) = "Self (" <> show x <> ")"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment