You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
"You can use a list like a stack to get the first element"
(= :a (peek '(:a :b :c :d :e)))
I believe this should be a queue instead of a stack, since a stack is last in first out. Since '(:a :b :c :d :e) the last element is :e this should be returned. A queue is first in first out so we pop the first element put in which would be :a. Please correct me if i'm wrong.
The text was updated successfully, but these errors were encountered:
For lists, it's definitely a stack - "last in first out" refers not to the ordering as you look at the data structure, but to the order in which elements are inserted and removed. So the last element to be inserted would be the first one to come back out.
Here's a lein repl session with similar examples to that koan:
user=> (cons :a '(:b :c :d :e)) ;; adding :a to the *front* of the list
(:a :b :c :d :e)
user=> (conj '(:a :b :c :d) :e) ;; adding :e to the front using conj
(:e :a :b :c :d)
user=> (peek '(:a :b :c :d :e)) ;; "peeking" at the last element inserted, :a
:a
user=> (pop '(:a :b :c :d :e)) ;; removing the last element added, :a
(:b :c :d :e)
Basically, it's efficient to add elements to the front of a list, and it's efficient to remove elements from the front of a list. And adding & removing from the same end is what a stack does. With a queue ("first in first out"), we'd expect to add on one end, and remove from the other end.
"Insert" (or "add") and "remove" take on a little different meaning due to the immutability of the data structures, but hopefully this sheds some more light on why the list gets used like a stack!
I have a question regarding the following koan:
"You can use a list like a stack to get the first element"
(= :a (peek '(:a :b :c :d :e)))
I believe this should be a queue instead of a stack, since a stack is last in first out. Since '(:a :b :c :d :e) the last element is :e this should be returned. A queue is first in first out so we pop the first element put in which would be :a. Please correct me if i'm wrong.
The text was updated successfully, but these errors were encountered: