How do I handle a variable number of arguments passed to a function in Racket?

前端 未结 3 554
名媛妹妹
名媛妹妹 2021-01-19 16:15

I like creating functions which take an unlimited number of arguments, and being able to deal with them as a list. It\'s been useful to me when creating binary trees & I

3条回答
  •  灰色年华
    2021-01-19 16:53

    There's nothing improper about the list received as a variadic argument list (meaning: variable number of arguments). For example:

    (define test-list
      (lambda xs
        (length xs))) ; xs is a normal list, use it like any other list
    
    (test-list 1 2 3 4)
    => 4
    

    In the above example, the xs parameter is a normal, plain, vanilla list, there's nothing improper about it. You can iterate over it as you would over any other list. There's no need to car it, it's already a list! Also, notice that the same function can be written like this:

    (define (test-list . xs)
      (length xs))   ; xs is a normal list, use it like any other list
    

    Just for reference: an improper list is one that does not end with the null list. For example: '(1 2 3 . 4). Again, that's not how a variadic argument list looks.

提交回复
热议问题