Add filterA to Prelude (#5809)

* CHANGELOG_BEGIN

Added filterA to Prelude.

* Update compiler/damlc/daml-stdlib-src/DA/Internal/Prelude.daml

Co-authored-by: Shayne Fletcher <shayne@shaynefletcher.org>

* Removed not so useful comment.

* Moved filterA from Prelude to Action.

* filterA is a one-liner now.

* Provided more meaningful example to filterA.

* Added test for filterA.

* Removed failing doctest.
CHANGELOG_END

Co-authored-by: Shayne Fletcher <shayne@shaynefletcher.org>
This commit is contained in:
Tamás Kálcza 2020-05-04 19:03:43 +02:00 committed by GitHub
parent 572b21e882
commit 6f1d2211d6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 41 additions and 1 deletions

View File

@ -59,6 +59,15 @@ foldl1A : Action m => (a -> a -> m a) -> [a] -> m a
foldl1A f (x :: xs) = foldlA f x xs
foldl1A _ [] = error "foldl1M: empty list"
-- | Filters the list using the applicative function: keeps only the elements where the predicate holds.
-- Example: given a collection of Iou contract IDs one can find only the GBPs.
--
-- ```
-- filterA (fmap (\iou -> iou.currency == "GBP") . fetch) iouCids
-- ```
filterA : Applicative m => (a -> m Bool) -> [a] -> m [a]
filterA p = foldr (\x -> liftA2 (\pHolds -> if pHolds then (x ::) else identity) (p x)) (pure [])
-- | `replicateA n act` performs the action `n` times, gathering the
-- results.
replicateA : (Applicative m) => Int -> m a -> m [a]

View File

@ -624,7 +624,7 @@ null : [a] -> Bool
null [] = True
null _ = False
-- | Filter the list using the function: keep only the elements where the predicate holds.
-- | Filters the list using the function: keep only the elements where the predicate holds.
filter : (a -> Bool) -> [a] -> [a]
filter p = foldr (\x xs -> if p x then x :: xs else xs) []

View File

@ -0,0 +1,31 @@
-- Copyright (c) 2020, Digital Asset (Switzerland) GmbH and/or its affiliates.
-- All rights reserved.
module ActionTest where
import DA.Assert
import DA.Action
import Iou12
testFilterA: Scenario ()
testFilterA = scenario do
bank <- getParty "Acme Bank"
alice <- getParty "Alice"
bob <- getParty "Bob"
charlie <- getParty "Charlie"
let
aliceIou = Iou bank alice "USD" 1.23 []
bobIou = Iou bank bob "GBP" 2.34 []
charlieIou = Iou bank charlie "EUR" 3.45 []
ious = [aliceIou, bobIou, charlieIou]
iouIds <- bank `submit` forA ious create
aliceIouIds <- bank `submit` filterA (fmap (\iou -> iou.owner == alice) . fetch) iouIds
aliceIous <- bank `submit` forA aliceIouIds fetch
[aliceIou] === aliceIous
largeIouIds <- bank `submit` filterA (fmap (\iou -> iou.amount > (2.0 : Decimal)) . fetch) iouIds
largeIous <- bank `submit` forA largeIouIds fetch
[bobIou, charlieIou] === largeIous