Trying to get this code to work, can't understand where to put the argument in and keep getting errors

*爱你&永不变心* 提交于 2019-12-31 05:08:28

问题


Define the function iota1(n, m) that takes positive integers n, m with n < m as input, and outputs the list (n,n+1,n+2,...,m)

I've tried switching the code around multiple times but cannot seem to get it to function and display a list the right way

(define (iota1 n m)
  (if (eq? n 0)
      '()
      (append (iota1 (< n m) (+ n 1)) (list n))))

回答1:


There's a few oddities to the code you provided, which I've formatted for readability:

(define (iota1 n m)
  (if (eq? n 0)
      '()
      (append (iota (< n m) (+ n 1))
              (list n))))

The first is that the expression (< n m) evaluates to a boolean value, depending on whether n is less than m or not. When you apply iota to (< n m) in the expression (iota (< n m) (+ n 1)), you are giving iota a boolean value for its first argument instead of a positive integer.

Secondly, the use of append is strange here. When constructing a list in Racket, it's much more common to use the function cons, which takes as arguments a value, and a list, and returns a new list with the value added to the front. For example,

(append '(3) (append '(4) (append '(5) '()))) ==> '(3 4 5)
(cons 3 (cons 4 (cons 5 '())))                ==> '(3 4 5)

It's a good idea to opt for using cons instead of append because it's simpler, and because it is faster, since cons does not traverse the entire list like append does.

Since this sounds a bit like a homework problem, I'll leave you with a "code template" to help you find the answer:

; n : integer
; m : integer
; return value : list of integers
(define (iota1 n m)
  (if (> n m)                  ; base case; no need to do work when n is greater than m
      ...                      ; value that goes at the end of the list
      (cons ...                ; the value we want to add to the front of the list
            (iota1 ... ...)))) ; the call to iota, generating the rest of the list



回答2:


Welcome to the racket world, my version is here:

#lang racket

(define (iota1 n m)
  (let loop ([loop_n n]
             [result_list '()])
    (if (<= loop_n m)
        (loop
         (add1 loop_n)
         (cons loop_n result_list))
        (reverse result_list))))


来源:https://stackoverflow.com/questions/55325304/trying-to-get-this-code-to-work-cant-understand-where-to-put-the-argument-in-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!