Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

confusion regarding "you can use a list as a stack to get the first element" koan. #169

Open
Daniel-Jacob opened this issue Nov 16, 2021 · 1 comment

Comments

@Daniel-Jacob
Copy link

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.

@trptcolin
Copy link
Member

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants