Following James's description, I would image constantly's
implementation to look something like the following.

(defn constantly [value] #(identity value))

If you haven't seen the # macro before, the form below is equivalent.

(defn constantly [value] (fn [] (identity value)))

Making use of Chris Houser's fine repl-utils library, you can easily
view the source at the REPL.

user=> (clojure.contrib.repl-utils/source constantly)
(defn constantly
  "Returns a function that takes any number of arguments and returns
x."
  [x] (fn [& args] x))

Seems I wasn't too far off, the canonical version allows any number of
args to be passed, but still just returns the value given at the time
of declaration.  I think it's safe to view constantly as a function
wrapper around 'identity'.

user=> (clojure.contrib.repl-utils/source identity)
(defn identity
  "Returns its argument."
  [x] x)

That is, I would view constantly to be the same as identity except it
returns a function which can be passed around, rather than the value
itself.

Finally, you could just as well do '#(identity the-value)' and get the
same result.

user=> (= (#(identity "ab")) ((constantly "ab")))
true

Sorry if I beat this to death; some of it was for my own learning and
benefit.

On Jan 25, 2:08 pm, wubbie <sunj...@gmail.com> wrote:
> thanks James,
> I'll have a look.
>
> -sun
>
> On Jan 25, 2:00 pm, James Reeves <weavejes...@googlemail.com> wrote:
>
> > On Jan 25, 5:34 pm, wubbie <sunj...@gmail.com> wrote:
>
> > > What's the typical usage of fn constantly ?
>
> > When you need a function that constantly returns the same result :)
>
> > That probably doesn't tell you any more than you know already, so I'll
> > give you a real world use. My rnd-utils library has a function
> > generating random strings that match a regular expression. It does
> > this by converting a regex into a sequence of functions, and then
> > concatenating the results into a string.
>
> > So a regex like "ab[def]" would be converted into two functions:
> > [(constantly "ab") (rnd-choice "def")]
>
> > This can then be turned into a string using: (apply str (map apply
> > function-sequence))
>
> > - James
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To post to this group, send email to clojure@googlegroups.com
To unsubscribe from this group, send email to 
clojure+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to