librelist archives

« back to archive

Variadic functions in 4Clojure problems (!!! my solution Included !!!)

Variadic functions in 4Clojure problems (!!! my solution Included !!!)

From:
Ali Baitam
Date:
2013-05-29 @ 23:22
How can I write the variadic solution for problem
23<http://www.4clojure.com/problem/23>(reverse a sequence) in the
provided blank space?

and generally speaking can an anonymous function be variadic?


```
(defn r-seq
  "reverses a seq"
  ([s]
    (r-seq s []))
  ([s rev]
    (if (empty? s)
      (seq  rev)
      (recur (butlast s) (conj rev (last s))))))


; 4clojure tests
(= (r-seq [1 2 3 4 5]) [5 4 3 2 1])
(= (r-seq (sorted-set 5 7 2 7)) '(7 5 2))
(= (r-seq [[1 2] [3 4] [5 6]]) [[5 6] [3 4] [1 2]])
```

Thanks
Ali

Re: [foray] Variadic functions in 4Clojure problems (!!! my solution Included !!!)

From:
Eric Pritchett
Date:
2013-05-29 @ 23:40
On Wed, May 29, 2013 at 6:22 PM, Ali Baitam <abaitam@gmail.com> wrote:
>
> can an anonymous function be variadic?


(fn [& more] (doseq [x more] (println x)))

Above is a variadic anonymous function that takes in a variable number of
arguments and prints them out to standard out.

On Wed, May 29, 2013 at 6:22 PM, Ali Baitam <abaitam@gmail.com> wrote:
>
> How can I write the variadic solution for problem 23?

Good question. However, it might be worth pointing out that there is a
simpler variadic solution to this problem using built in Clojure functions.
You might want to take a look at conj and it's effects on lists vs vectors
as a starting place.

Re: [foray] Variadic functions in 4Clojure problems (!!! my solution Included !!!)

From:
Ali Baitam
Date:
2013-05-30 @ 00:02
Thanks Eric,
I meant to ask about multi-arity anonymous functions not variadic :)

As to the problem I did look into another solution but the sorted-set test
failed:

```
(defn r-seq1
  [s]
  (let [idx (range (count s))
        r-idx (map #(- (dec (count s)) %) idx)]
    (map #(nth s %) r-idx)))
```

I'll look into your suggestion now.

Thanks


On Wed, May 29, 2013 at 7:40 PM, Eric Pritchett <
eric.a.pritchett.che@gmail.com> wrote:

>
> On Wed, May 29, 2013 at 6:22 PM, Ali Baitam <abaitam@gmail.com> wrote:
> >
> > can an anonymous function be variadic?
>
>
> (fn [& more] (doseq [x more] (println x)))
>
> Above is a variadic anonymous function that takes in a variable number of
> arguments and prints them out to standard out.
>
> On Wed, May 29, 2013 at 6:22 PM, Ali Baitam <abaitam@gmail.com> wrote:
> >
> > How can I write the variadic solution for problem 23?
>
> Good question. However, it might be worth pointing out that there is a
> simpler variadic solution to this problem using built in Clojure functions.
> You might want to take a look at conj and it's effects on lists vs vectors
> as a starting place.
>