Skip to content

Instantly share code, notes, and snippets.

@tmountain
Created October 24, 2018 12:41
Show Gist options
  • Save tmountain/c7a66e4bc1bafeb811c554d6921c1507 to your computer and use it in GitHub Desktop.
Save tmountain/c7a66e4bc1bafeb811c554d6921c1507 to your computer and use it in GitHub Desktop.
Purescript by Example Solutions (Chapter 4)
module Even where
import Prelude
import Data.Foldable (product)
import Data.Array (concatMap, null, sort, filter, length, (..))
import Data.Array.Partial (head, tail)
import Partial.Unsafe (unsafePartial)
import Control.MonadZero (guard)
-- pattern matching version
even :: Int -> Boolean
even 0 = true
even 1 = false
even n = if n < 0 then even (-n) else even (n - 2)
-- case statement version
even' :: Int -> Boolean
even' x =
case x of
0 -> true
1 -> false
n -> if n < 0 then even (-n) else even (n - 2)
-- one argument version
evenInts :: Array Int -> Int
evenInts xs =
if null xs
then 0
else
let
isEven = even $ unsafePartial $ head xs
toAdd = if isEven then 1 else 0
in
toAdd + evenInts (unsafePartial tail xs)
-- two argument version
evenInts' :: Int -> Array Int -> Int
evenInts' acc xs =
if null xs
then acc
else
let
isEven = even $ unsafePartial $ head xs
toAdd = if isEven then 1 else 0
in
evenInts' (acc + toAdd) (unsafePartial tail xs)
-- write a (point-free) function that calculates the squares of an array of numbers
-- sqs (1..10) -> [2,4,6,8,10]
dbl x = x + x
sqs = map dbl
-- use filter to remove negative numbers
-- isPos (-3 .. 3) -> [0,1,2,3]
isPos x = x >= 0
remNeg = filter isPos
-- define an infix synonym <$?> for filter
infix 8 filter as <$?>
posNums = isPos <$?> (-3 .. 3)
-- nested lambda version of pairs''
pairs'' n =
concatMap (\i ->
map (\j -> [i, j]) (i .. n)
) (1 .. n)
-- find factors using filter and do notation
factors :: Int -> Array (Array Int)
factors n = filter (\xs -> product xs == n) $ do
i <- 1 .. n
j <- i .. n
pure [i, j]
-- find prime numbers using factors
isPrime :: Int -> Boolean
isPrime x = (length $ factors x) == 1
primeFilter :: Array Int -> Array Int
primeFilter = filter isPrime
-- cartesian product of two arrays
prod xs ys = do
x <- xs
y <- ys
pure [x, y]
-- pythagorean triples
triple :: Int -> Array Int
triple c = do
a <- 1 .. c
b <- 1 .. a
guard $ (a*a) + (b*b) == (c*c)
[a, b, c]
notEmpty :: Array Int -> Boolean
notEmpty = not null
sortedTriple :: Int -> Array Int
sortedTriple = sort <<< triple
triples = filter notEmpty $ sort $ map sortedTriple (1 .. 100)
-- factorizations (todo...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment