HomeMathEmailBlogGitHub

Clojure nth vs get

2023-05-25

nth and get look almost identical on the surface. They both get the nth element in a sequence.

(nth [1 3 5] 2) ;=> 5
(get [1 3 5] 2) ;=> 5

But there are a couple nuances that differentiate them.

One difference is the way that they handle out-of-bounds cases.

(nth [1 3 5] 3) ;=> IndexOutOfBoundsException
(get [1 3 5] 3) ;=> nil

nth can still handle out-of-bounds cases with a not-found argument.

(nth [1 3 5] 3 "Hello") ;=> "Hello"

The upside to get is that it works with maps, while nth does not.

(get {:a 1 :b 2} :b) ;=> 2