Thanks for the reply. :)

On Wednesday, November 16, 2016 at 11:44:50 PM UTC+9, Alex Miller wrote:
>
>
>
> On Tuesday, November 15, 2016 at 10:11:34 PM UTC-6, Eunmin Kim wrote:
>>
>> Hi! I had a question while reading Functional Programming in Scala book.
>>
>> The following code is Exercise 2:
>>
>> // Exercise 2: Implement a polymorphic function to check whether
>> // an `Array[A]` is sorted
>>
>> def isSorted[A](as: Array[A], gt: (A,A) => Boolean): Boolean = {
>>   @annotation.tailrec
>>   def go(n: Int): Boolean =
>>     if (n >= as.length-1) true
>>     else if (gt(as(n), as(n+1))) false
>>     else go(n+1)
>>
>>   go(0)
>> }
>>
>> In the above code, Generic typ parameter(A) is displayed. How should I 
>> express it in clojure spec?
>>
>
> Because Clojure doesn't have generics, there is no direct representation 
> of A in the Clojure version. If you want to ensure that all elements of the 
> collection are of the same type, then say that.
>
> (defn same-type? [coll]
>   (or (empty? coll)
>          (let [t (class (first coll))]
>            (every? #(= t (class %)) coll))))
>
> (s/fdef sorted-coll?
>   :args (s/cat :as (s/and (s/coll-of any?) same-type?)
>                      :ordered-fn? ifn?) ;; cheating for brevity
>   :ret boolean?)
>
>  
>
>> (defn sorted-coll? [as ordered-fn?]
>>   (loop [coll (seq as)]
>>     (cond 
>>       (= 1 (count coll)) true
>>
>
> just by inspection, this is broken for empty collections - should be <= 1 
> here
>  
>
>>       (not (ordered-fn? (first coll) (second coll))) false
>>       :else (recur (rest coll)))))
>>
>>
> And I would be remiss not to mention that 
> a) there is an existing sorted? predicate that I would use for this purpose
> b) the sorted set and map implementations in Clojure already require that 
> elements are all of the same type for the comparator to work
>  
>

-- 
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
Note that posts from new members are moderated - please be patient with your 
first post.
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
--- 
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to