簡體   English   中英

Agda:返回列表的最后一個元素

[英]Agda: return the last element of a List

當我檢查agda-stdlib/src/Data/List/Base.agda我看到有沒有last的功能,但我看到agda-stdlib/src/Data/Vec/Base.agda功能的last

當我嘗試使用它時,雖然我得到了一些我不確定我理解的類型錯誤。

這就是我試圖稱呼它的方式: last (fromList todos)

在哪里

todos : List Todo

record Todo : Set where
  field
    text      : String
    completed : Bool
    id        : ℕ

我得到的錯誤是

Data.List.foldr (λ _ → suc) 0 todos != suc _n_31 of type ℕ
when checking that the expression fromList todos has type
Data.Vec.Vec Todo (1 + _n_31)

我猜這與last具有此簽名的事實有關:

last : ∀ {n} → Vec A (1 + n) → A

但是我很困惑,因為當我執行Cc Cl時:

last (fromList ?)

我得到這個目標

?0 : List Todo

我認為todos滿意。

我應該在這里更改什么以使其通過此錯誤? 還是有另一種方法來獲取List的最后一個元素?

謝謝!

編輯

我嘗試了不同的路線並決定用List替換Vec 但是,當我嘗試這樣做時,我又遇到了另一個錯誤,我不太明白

  Todo.completed (last (todos ∷ʳ record { text = text ; completed = false ; id = 1 }))
≡⟨⟩
  Todo.completed (record { text = text ; completed = false ; id = 1 })
false !=
Todo.completed
(last
 (todos ∷ʳ record { text = text ; completed = false ; id = 1 })
 | Data.Vec.initLast
   (todos ∷ʳ record { text = text ; completed = false ; id = 1 }))
of type Bool
when checking that the inferred type of an application
  false ≡ _y_45
matches the expected type
  Todo.completed
  (last
   (todos ∷ʳ record { text = text ; completed = false ; id = 1 }))
  ≡ false

我不確定這里的錯誤消息是什么意思。

編輯

我試圖將問題進一步簡化為

AddNat : ∀ {n : ℕ} → (Vec ℕ n) → (Vec ℕ (1 + n))
AddNat numbers = numbers ∷ʳ 1

AddNatLastAddedElementIsNat :
  ∀ {n : ℕ} (numbers : Vec ℕ (1 + n)) →
    last (AddNat numbers) ≡ 1
AddNatLastAddedElementIsNat numbers =
  begin
    last (AddNat numbers)
  ≡⟨⟩
    last (numbers ∷ʳ 1)
  ≡⟨⟩
    1
  ∎

但我仍然收到類似的錯誤:

1 != (last (numbers ∷ʳ 1) | Data.Vec.initLast (numbers ∷ʳ 1)) of
type ℕ
when checking that the expression 1 ∎ has type
last (numbers ∷ʳ 1) ≡ 1

為什么last (numbers ∷ʳ 1)顯示為類型(last (numbers ∷ʳ 1) | Data.Vec.initLast (numbers ∷ʳ 1)) 是否| 表示它是一個和類型,我需要在兩種情況下進行模式匹配? 謝謝!

fromList ?0中的目標確實具有List Todo類型,但是由於fromList ?0具有Vec _ (length ?0)類型,如果類型檢查器得出結論認為不可能沒有n這樣的length ?0是(定義)等於1 + n 在您的情況下,一旦您說?0 := todos就會發生這種情況,例如?0 := x ∷ todos會起作用。

通常,像last這樣的函數需要知道列表或向量是非空的,另一種方法是定義一個返回Maybe A而不是A的函數。

暫無
暫無

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

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