English 中文(简体)
我点的药头,我定的药头不工作了
原标题:my ordered predicate won t work

This function is supposed to return #t if the list e is incrementally ordered. The function doesn t work and I can t fix it.

(define (ordered e)
  (if (or (null? e) (> length(e) 1))
      #t
      (if (> (car e) (cadr e))
          #f
          (ordered (cdr e)))))
问题回答

问题所在的基数是错误的, 简单声明列表如果有不小于两个元素, 则命令列表会更容易( 且不易出错) 。 这就是在您的代码中造成问题的原因, 因为基数的大小写定义不清, 您的程序会进入第二个错误的大小写 。 当列表有小于两个元素时, 您不能使用 < code> cadr 。 要修正您的执行, 您可以这样做 :

(define (ordered e) 
  (if (< (length e) 2)
      #t 
      (if (> (car e) (cadr e))
          #f 
          (ordered (cdr e)))))

您可以使用 cond 来更简洁地表达这一问题的解决方案, 您可以避免使用 long (视实施情况而定, 这可能是一个 O(n) 操作), 类似 :

(define (ordered e)
  (cond ((or (null? e) (null? (cdr e))) #t)
        ((> (car e) (cadr e)) #f)
        (else (ordered (cdr e)))))




相关问题
How do I sort enum members alphabetically in Java?

I have an enum class like the following: public enum Letter { OMEGA_LETTER("Omega"), GAMMA_LETTER("Gamma"), BETA_LETTER("Beta"), ALPHA_LETTER("Alpha"), private final String ...

Grokking Timsort

There s a (relatively) new sort on the block called Timsort. It s been used as Python s list.sort, and is now going to be the new Array.sort in Java 7. There s some documentation and a tiny Wikipedia ...

Sorting twodimensional Array in AS3

So, i have a two-dimensional Array of ID s and vote count - voteArray[i][0] = ID, voteArray[i][1] = vote count I want the top 3 voted items to be displayed in different colors, so i have a 2nd Array -...

Linq operations against a List of Hashtables?

I m working with a set of legacy DAO code that returns an IList, where each Hashtable represents the row of a dynamically executed SQL query. For example, the List might contain the following records/...

C++ Array Sort Me

Stuck on an array sorter. Have to sort numbers from largest to smallest. I m trying two loops (one nested in the other). Here s the code: int counter=0; // inner counter int counter2=0; // outer ...

Can I Nest OrderBy in .NET?

This doesn t seem to work as I intend. VB.NET: Dim x = Model.Discussions.OrderByDescending(Function(d) d.Messages.OrderByDescending(Function(m) m.Sent).First.Sent) For Each d As Discussion In x ....

sorting elements javascript

I m looking for a way to sort my elements, but it isn t as easy as it sounds. Please let me explain My elements are grouped per 6 elements (thumbnails), each x represents a thumbnail However all ...

热门标签