@@ -20,7 +20,8 @@ open import Data.Nat.Base as ℕ using (ℕ; zero; suc; _+_; _*_ ; _≤_ ; s≤s
2020open import Data.Product.Base as Prod using (_×_; _,_; map₁; map₂′)
2121open import Data.Sum.Base as Sum using (_⊎_; inj₁; inj₂)
2222open import Data.These.Base as These using (These; this; that; these)
23- open import Function.Base using (id; _∘_ ; _∘′_; _∘₂_; const; flip)
23+ open import Function.Base
24+ using (id; _∘_ ; _∘′_; _∘₂_; _$_; const; flip)
2425open import Level using (Level)
2526open import Relation.Nullary.Decidable.Core using (does; ¬?)
2627open import Relation.Unary using (Pred; Decidable)
@@ -395,6 +396,24 @@ deduplicateᵇ : (A → A → Bool) → List A → List A
395396deduplicateᵇ r [] = []
396397deduplicateᵇ r (x ∷ xs) = x ∷ filterᵇ (not ∘ r x) (deduplicateᵇ r xs)
397398
399+ findᵇ : (A → Bool) → List A → Maybe A
400+ findᵇ p [] = nothing
401+ findᵇ p (x ∷ xs) = if p x then just x else findᵇ p xs
402+
403+ findIndexᵇ : (A → Bool) → (x : List A) → Maybe $ Fin (length x)
404+ findIndexᵇ p [] = nothing
405+ findIndexᵇ p (x ∷ xs) = if p x
406+ then just zero
407+ else mapMaybe suc (findIndexᵇ p xs)
408+
409+ findIndicesᵇ : (A → Bool) → List A → List ℕ
410+ findIndicesᵇ {A = A} p = h 0 where
411+ h : ℕ → List A → List ℕ
412+ h n [] = []
413+ h n (x ∷ xs) = if p x
414+ then n ∷ h (suc n) xs
415+ else h (suc n) xs
416+
398417-- Equivalent functions that use a decidable predicate instead of a
399418-- boolean function.
400419
@@ -436,6 +455,15 @@ derun R? = derunᵇ (does ∘₂ R?)
436455deduplicate : ∀ {R : Rel A p} → B.Decidable R → List A → List A
437456deduplicate R? = deduplicateᵇ (does ∘₂ R?)
438457
458+ find : ∀ {P : Pred A p} → Decidable P → List A → Maybe A
459+ find P? = findᵇ (does ∘ P?)
460+
461+ findIndex : ∀ {P : Pred A p} → Decidable P → (x : List A) → Maybe $ Fin (length x)
462+ findIndex P? = findIndexᵇ (does ∘ P?)
463+
464+ findIndices : ∀ {P : Pred A p} → Decidable P → List A → List ℕ
465+ findIndices P? = findIndicesᵇ (does ∘ P?)
466+
439467------------------------------------------------------------------------
440468-- Actions on single elements
441469
0 commit comments