Skip to content

Instantly share code, notes, and snippets.

@DonaldKellett
Created January 1, 2019 08:51
Show Gist options
  • Save DonaldKellett/75af59cfd522cd53d58e543ef2c57786 to your computer and use it in GitHub Desktop.
Save DonaldKellett/75af59cfd522cd53d58e543ef2c57786 to your computer and use it in GitHub Desktop.
PureScript by Example - 4.11 Guards - Exercise 1-4 Solutions
module Guards where
-- 4.11 Guards of PureScript by Example
-- Boilerplate code provided by PureScript by Example
import Prelude
import Data.Array
import Control.MonadZero (guard)
factors :: Int -> Array (Array Int)
factors n = do
i <- 1 .. n
j <- i .. n
guard (i * j == n)
pure [i, j]
-- Exercise 1
isPrime :: Int -> Boolean
isPrime n = n /= 1 && length (factors n) == 1
-- Exercise 2
cartesianProduct :: forall a. Array a -> Array a -> Array (Array a)
cartesianProduct arr1 arr2 = do
a <- arr1
b <- arr2
pure [a, b]
-- Exercise 3
pythagoreanTriples :: Int -> Array (Array Int)
pythagoreanTriples n = do
a <- 1 .. n
b <- a .. n
c <- b .. n
guard (a * a + b * b == c * c)
pure [a, b, c]
-- Exercise 4
factorizations :: Int -> Array (Array Int)
factorizations 1 = [[1]]
factorizations n = nubEq $ map sort $
map (filter (\m -> m /= 1)) $
concatMap (\m -> map (\arr -> m : arr) (factorizations (div n m))) $
filter (\m -> mod n m == 0) (2 .. n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment