簡體   English   中英

阿格達:返回空列表的頭尾

[英]Agda: Return head and tail of empty list

我正在學習agda並在列表上練習以獲得更好的理解。 現在我正在嘗試為列表編寫函數。 我很困惑如何返回空列表的頭部和尾部。 這是我的代碼:

data list (A : Set) : Set where
[]  : list A
_∷_ : A → list A → list A

Null : {A : Set} → (list A) → Bool
Null [] = true
Null (x ∷ a) = false

tail :  {A : Set} → (list A) → A
tail [] = {!!}
tail (x ∷ []) = x  
tail (x ∷ a) = tail a

head : {A : Set} → (list A) →  A
head [] = {!!}
head (x ∷ a) = x

我找到的一個解決方法是,我返回一個包含第一個和最后一個成員的列表,而不是返回第一個和最后一個成員,如下所示:

tail :  {A : Set} → (list A) → (list A)
tail [] = []
tail (x ∷ []) = x ∷ []  
tail (x ∷ a) = tail a

head : {A : Set} → (list A) → (list A)
head [] = []
head (x ∷ a) = (x ∷ [])

但我仍然對如何返回頭部和尾部值感到困惑。 我怎樣才能做到這一點?

PS不是作業。 在課堂上提前幾英里

在Agda中,函數是總的:如果你有head : {A : Set} -> list A -> A ,那么它需要在所有列表上定義。 但是,對於head []你不能為某個任意類型A想象一個元素(想象head ([] : list Void) ...)

問題是你的head承諾太多了。 事實上,你可以返回任何列表的第一個元素; 你只能用於非空列表。 所以你需要改變head要么單獨證明空虛 ,要么采用非空列表作為參數:

module SeparateProof where
  open import Data.List
  open import Data.Bool
  open import Data.Unit

  head : {A : Set} → (xs : List A) → {{nonEmpty : T (not (null xs))}} → A
  head [] {{nonEmpty = ()}} -- There's no way to pass a proof of non-emptiness for an empty list!
  head (x ∷ xs) = x

module NonEmptyType where
  open import Data.List.NonEmpty hiding (head)

  head : {A : Set} → List⁺ A → A
  head (x ∷ xs) = x -- This is the only pattern matching a List⁺ A!

這是一個用詞不當,最后你不想尾巴,對於正確的尾部函數,你可以看看標准庫的Data \\ List \\ Base.agda中的drop:

drop : ∀ {a} {A : Set a} → ℕ → List A → List A
drop zero    xs       = xs
drop (suc n) []       = []
drop (suc n) (x ∷ xs) = drop n xs
--e.g. drop 1
tail : ∀ {a} {A : Set a} → List A → List A
tail []       = []
tail (x ∷ xs) = xs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM