I am writing Coq code that needs to modify lists, particularly by accessing an index i
, applying a function to that element, and replacing it back. I know I can acces the elemenent of a list by using nth
as defined in Coq.Lists.List
. Then, I could apply the function to this element, but what would be the best way to insert the element back into the original list using the Coq.Lists.List
library?
I currently have the following code:
Definition bv (n : nat) := list bool.
Definition get_bv {n : nat} (i : nat) (v : bv n) := nth i v false.
Notation " v [ i ]" := (get_bv i v) (at level 0).
So given the function that I want to apply f : bool -> bool
, I could do f(v[i])
, but I'm not sure how to replace it back.
If you want to apply the same function to every element of a list,
you can use map
. Instead, if you want to only replace one
single element of a list, you may need to write your own replace function. For example:
Require Import List.
Import ListNotations.
Fixpoint replace {A : Type} (l : list A) (i : nat) (v : A) :=
match l with
| [] => []
| a :: l1 => match i with
| 0 => v :: l1
| S i1 => a :: replace l1 i1 v
end
end.
Compute replace [true; false; true] 2 false.