From Stdlib Require Import Streams.
From Stdlib Require Import List.
Import ListNotations.

Sequences

Another thing we will need is sequences.
By sequences, I mean here both finite sequences (which one can represent as lists) and infinite sequences (which one can represent as streams). Here, we will define basic operations on these sequences and lemmas which will be usefull in the following.
Inductive Sequence (T : Type) : Type :=
  | Finite (l : list T) : Sequence T
  | Infinite (s : Stream T) : Sequence T
  .
Arguments Finite {T}.
Arguments Infinite {T}.

Definition finite {T : Type} (s : Sequence T) : Prop :=
  match s with
  | Finite _ ⇒ True
  | Infinite _ ⇒ False
  end.

We can build sequence constructor.
Definition ConsSeq {T : Type} (x : T) (s : Sequence T) : Sequence T :=
  match s with
  | Finite l ⇒ Finite (x::l)
  | Infinite s ⇒ Infinite (Cons x s)
  end.
And an extented option type expliciting infinteness will prove useful.
Inductive OptionSeq (T : Type) : Type :=
  | NoneSeq
  | SomeSeq (x : T)
  | NonfiniteSeq
  .
Arguments NoneSeq {T}.
Arguments SomeSeq {T}.
Arguments NonfiniteSeq {T}.

Fixpoint stream_concat {T : Type} (l : list T) (s : Stream T) : Stream T :=
  match l with
  | nil ⇒ s
  | x::ls ⇒ Cons x (stream_concat ls s)
  end.

Fixpoint last_error_list {A : Type} (l:list A) : OptionSeq A :=
  match l with
    | [] ⇒ NoneSeq
    | [a] ⇒ SomeSeq a
    | a :: l' ⇒ last_error_list l'
  end.

Definition last_error {A : Type} (s : Sequence A) : OptionSeq A :=
  match s with
  | Finite l ⇒ last_error_list l
  | Infinite _ ⇒ NonfiniteSeq
  end.