12/08/2020 Code (Week 2 Video)
Code (Week 2 Video)
Using the same ShapeGraphics library found in this week’s exercise. Ellipses Example
module Ellipses where
— needed to display the picture in the playground
import Codec.Picture
— our line graphics programming interface
import ShapeGraphics
simpleEllipsePic :: Float -> Picture
simpleEllipsePic n
= map greenEllipse
[0, pi/n .. (n-1)*pi/n]
where
centre :: Point
centre = Point 400 400
greenEllipse :: Float -> PictureObject
greenEllipse angle
= Ellipse centre 250 70 angle
(colourFor angle)
Solid SolidFill
colourFor angle
= let x = round (255 * angle / pi)
in Colour (255 – x) 128 x 84
writeToFile pic
= writePng “output.png”
(drawPicture 3 pic)
Non-Empty Lists
data NonEmpty a = One a | Cons a (NonEmpty a)
www.cse.unsw.edu.au/~cs3141/20T2/Week 02/1Vid/Code.html
1/2
12/08/2020 Code (Week 2 Video)
Functors
maybeMap :: (a -> b) -> Maybe a -> Maybe b
maybeMap f Nothing = Nothing
maybeMap f (Just x) = Just (f x)
maybeMap f mx = case mx of
Nothing -> Nothing
Just x -> Just (f x)
— type level:
— (,) :: * -> (* -> *) — (,) x :: * -> *
instance Functor ((,) x) where
— fmap :: (a -> b) -> f a -> f b
— fmap :: (a -> b) -> (,) x a -> (,) x b
— fmap :: (a -> b) -> (x,a) -> (x, b)
fmap f (x,a) = (x, f a)
— type level:
— (->) :: * -> (* -> *) — (->) x :: * -> *
instance Functor ((->) x) where
— fmap :: (a -> b) -> f a -> f b
— fmap :: (a -> b) -> (->) x a -> (->) x b
— fmap :: (a -> b) -> (x -> a) -> (x -> b)
fmap = (.)
safeHead :: NonEmpty a -> a
safeHead (One a) = a
safeHead (Cons a _) = a
append :: NonEmpty a -> NonEmpty a -> NonEmpty a
append (One a) ls = Cons a ls
append (Cons a as) ls = Cons a (append as ls)
www.cse.unsw.edu.au/~cs3141/20T2/Week 02/1Vid/Code.html
2/2