Skip to content

Instantly share code, notes, and snippets.

@AdamSaleh
Created August 30, 2016 16:12
Show Gist options
  • Save AdamSaleh/e4b1608b7de5558bf321f343328cd362 to your computer and use it in GitHub Desktop.
Save AdamSaleh/e4b1608b7de5558bf321f343328cd362 to your computer and use it in GitHub Desktop.
module Main where
import Prelude
import Data.Array ((..))
import Data.Foldable (for_)
import Control.MonadPlus (guard)
import Control.Monad.Eff.Console (logShow)
import Data.Functor (class Functor)
import Control.Monad.Free (Free, liftF)
data AdderF k =
Add Int (Boolean -> k)
| Clear k
| Total (Int -> k)
instance functorAdderF :: Functor AdderF where
map f (Add x k) = Add x (f <<< k)
map f (Clear k) = Clear (f k)
map f (Total k) = Total (f <<< k)
type Adder a = Free AdderF a
add :: Int -> Adder Boolean
add x = liftF $ Add x id
clear :: Adder Unit
clear = liftF $ Clear unit
total :: Adder Int
total = liftF $ Total id
findLimit :: Adder Int
findLimit = do
t <- total
clear
pure t
-- Find Pythagorean triples using an array comprehension.
triples :: Int -> Array (Array Int)
triples n = do
z <- 1 .. n
y <- 1 .. z
x <- 1 .. y
guard $ x * x + y * y == z * z
pure [x, y, z]
main = for_ (triples 20) logShow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment