Skip to content

refact factorize using array reverse and use already existent code #385

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 6 additions & 14 deletions exercises/chapter4/test/no-peeking/Solutions.purs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module Test.NoPeeking.Solutions where

import Prelude
import Control.MonadZero (guard)
import Data.Array (catMaybes, cons, filter, find, head, last, length, nub, null, tail, (..))
import Data.Array (catMaybes, cons, filter, find, head, last, length, nub, null, tail, (..), reverse)
import Data.Foldable (foldl)
import Data.Int (rem, quot)
import Data.Maybe (Maybe(..), fromMaybe, maybe)
Expand Down Expand Up @@ -58,19 +58,11 @@ triples n = do

-- | Provide the prime numbers that, multiplied together, make the argument.
factorize :: Int -> Array Int
factorize n = factorize' 2 n []
where
factorize' :: Int -> Int -> Array Int -> Array Int
factorize' _ 1 result = result

factorize' divisor dividend result =
let
remainder = rem dividend divisor
in
if remainder == 0 then
factorize' (divisor) (quot dividend divisor) (cons divisor result)
else
factorize' (divisor + 1) dividend result
factorize n = do
f <- reverse $ factors n
fi <- reverse $ f
guard $ isPrime fi
pure fi

allTrue :: Array Boolean -> Boolean
allTrue bools = foldl (\acc bool -> acc && bool) true bools
Expand Down