Skip to content

Instantly share code, notes, and snippets.

@stevemohapibanks
Created September 24, 2010 14:42
Show Gist options
  • Select an option

  • Save stevemohapibanks/595497 to your computer and use it in GitHub Desktop.

Select an option

Save stevemohapibanks/595497 to your computer and use it in GitHub Desktop.
(defn rpad-seq
[s n x]
(if (< (count s) n)
(seq (apply conj (vec s) (replicate (- n (count s)) x)))
s))
=> (rpad-seq (list "a" "b" "c") 10 "d")
("a" "b" "c" "d" "d" "d" "d" "d" "d" "d")
Thanks to Mr Purcell for the refactor below:
(defn rpad-seq [s n x]
(take n (concat s (repeat x))))
@stevemohapibanks

Copy link
Copy Markdown
Author

If anyone knows if there's a standard clojure API function that does this (or knows how to refactor this to be more idiomatic) please do.

@liebke

liebke commented Sep 24, 2010

Copy link
Copy Markdown

An alternative implementation is:

(defn rpad-seq [s n x](concat s %28repeat %28- n %28count s%29%29 x%29))

@purcell

purcell commented Sep 24, 2010

Copy link
Copy Markdown

Or, without needing to count s:

(defn rpad-seq [s n x]
  (take n (concat s (repeat x))))

@liebke

liebke commented Sep 24, 2010

Copy link
Copy Markdown

purcell, much nicer.

@purcell

purcell commented Sep 24, 2010

Copy link
Copy Markdown

Clojure's awesome.

@stevemohapibanks

Copy link
Copy Markdown
Author

Awesome, thanks chaps.

And my Clojure learning continues :)

@wmacgyver

Copy link
Copy Markdown

try (take 10 (lazy-cat a (repeat "d")))
assuming a is your list. use lazy-cat to produce a lazy collection, and use take to get as many as you need.

in function form, it'd be (defn rpad-seq [s n x](take n %28lazy-cat s %28repeat x%29%29)

@purcell

purcell commented Sep 24, 2010

Copy link
Copy Markdown

concat is lazy in recent versions of Clojure, so the lazy-cat formulation is pretty much equivalent to that above. It's definitely important to be aware of when seqs are and are not lazy.

@wmacgyver

Copy link
Copy Markdown

precisely why I tend to use lazy-cat, it's a reminder that lazy is at work.

@purcell

purcell commented Sep 24, 2010

Copy link
Copy Markdown

or not at work, as the case may be!

@stevemohapibanks

Copy link
Copy Markdown
Author

Any programming language that has a function called lazy-cat is cool with me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment