Skip to content

Instantly share code, notes, and snippets.

@DonaldKellett
Created January 1, 2019 10:15
Show Gist options
  • Save DonaldKellett/cc0ca184fdedca4dea874df60d026beb to your computer and use it in GitHub Desktop.
Save DonaldKellett/cc0ca184fdedca4dea874df60d026beb to your computer and use it in GitHub Desktop.
PureScript by Example - 4.15 Prefer Folds to Explicit Recursion - Exercise 1, 3, 4 Solutions
module Folds where
import Prelude
import Data.Foldable
import Data.Array.Partial
import Partial.Unsafe
-- Exercise 1
allTrue :: Array Boolean -> Boolean
allTrue = foldl (&&) true
-- Exercise 3
count :: forall a. (a -> Boolean) -> Array a -> Int
count f arr = count' f arr 0
where
count' :: forall a. (a -> Boolean) -> Array a -> Int -> Int
count' _ [] acc = acc
count' f arr acc = count' f (unsafePartial tail arr) (acc + (if f (unsafePartial head arr) then 1 else 0))
-- Exercise 4
reverse :: forall a. Array a -> Array a
reverse = foldl (\arr elem -> [elem] <> arr) []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment