icyrock.com

Home

PureScript solutions to Project Euler - problem 2

2017-Nov-29 21:48
purescriptproject-euler

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
module Euler002Test (euler2suite) where
 
import Prelude
 
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Assert as Assert
 
import Euler002 (euler2)
 
euler2suite :: forall e. TestSuite e
euler2suite =
  suite "Euler 2" do
    test "Warmup" do
      Assert.equal 44 (euler2 89)
    test "Real" do
      Assert.equal 4613732 (euler2 4000000)

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
module Euler002 (euler2) where
 
import Prelude
 
import Data.Foldable (sum)
import Data.List.Lazy (filter, iterate, takeWhile)
 
euler2 :: Int -> Int
euler2 n =
  iterate (\{a, b} -> {a: b, b: a + b}) {a: 1, b: 2}
  # takeWhile (\{a, b} -> b <= n)
  # map (\{a, b} -> b)
  # filter (\e -> e `mod` 2 == 0)
  # sum