【问题标题】:Scheme - Optional arguments and default values方案 - 可选参数和默认值
【发布时间】:2016-08-23 04:52:04
【问题描述】:

我目前正在研究 Scheme,按照我的理解,过程可以采用任意数量的参数。

我一直在尝试解决这个问题,但我很难掌握这个概念。

例如,假设我想根据用户提供的信息编写欢迎消息。

如果用户提供了名字和姓氏,程序喊写:

Welcome, <FIRST> <LAST>!
;; <FIRST> = "Julius", <LAST>= "Caesar"
Welcome, Julius Caesar!

否则,程序应该引用一个默认值,指定为:

Welcome, Anonymous Person!

我的代码有以下大纲,但正在努力完成它。

(define (welcome . args)
  (let (('first <user_first>/"Anonymous")
        ('last <user_last>/"Person"))
    (display (string-append "Welcome, " first " " last "!"))))

示例用法:

(welcome) ;;no arguments
--> Welcome, Anonymous Person!
(welcome 'first "John") ;;one argument
--> Welcome, John Person!
(welcome 'first "John" 'last "Doe") ;;two arguments
--> Welcome, John Doe!

非常感谢任何帮助!

【问题讨论】:

    标签: arguments scheme racket optional-parameters


    【解决方案1】:

    在 Racket 中,执行此操作的方法是使用 keyword arguments。您可以在声明参数时使用关键字参数定义一个函数我的写作#:keyword argument-id

    (define (welcome #:first first-name #:last last-name)
      (display (string-append "Welcome, " first-name " " last-name "!")))
    

    你可以这样称呼:

    > (welcome #:first "John" #:last "Doe")
    Welcome, John Doe!
    

    但是,您想要的是使它们成为可选的。为此,您可以在参数声明中写入#:keyword [argument-id default-value]

    (define (welcome #:first [first-name "Anonymous"] #:last [last-name "Person"])
      (display (string-append "Welcome, " first-name " " last-name "!")))
    

    这样如果你在某个函数调用中不使用那个关键字,它就会被默认值填充。

    > (welcome)
    Welcome, Anonymous Person!
    > (welcome #:first "John")
    Welcome, John Person!
    > (welcome #:first "John" #:last "Doe")
    Welcome, John Doe!
    > (welcome #:last "Doe" #:first "John")
    Welcome, John Doe!
    

    【讨论】:

    • 这不接受任意数量的参数。
    • 我不打算让它接受任意数量的参数;如果你需要,你可以写(define (welcome #:first first-name #:last last-name . rest-args) ...)
    【解决方案2】:

    @Alex Knauth 的回答很棒。那是我不知道的事情。

    这里有一个替代方案,虽然它不太灵活

    (define (welcome (first "Anonymous") (last "Person"))
      (displayln (string-append "Welcome, " first " " last "!")))
    

    这非常适合您的基本要求

    > (welcome)
    Welcome, Anonymous Person!
    > (welcome "John")
    Welcome, John Person!
    > (welcome "John" "Doe")
    Welcome, John Doe!
    

    但是,Alex 的解决方案有两个明显的优势。

    1. 可以按任意顺序调用参数
    2. 姓氏可以不指定名字

    【讨论】:

    • 你的答案可以通过定义(define welcome (lambda args (string-append "Welcome, " (or (assq-ref args 'first) "Anonymous") " " (or (assq-ref args 'last) "Person"))))然后调用(welcome '(first . "John") '(last . "Doe"))来改进。
    • 您应该将此作为问题的另一个答案提交。这是一个不错的选择,但如果我想为参数添加关键字,我可能只会使用 Alex 的解决方案。谢谢分享^_^
    猜你喜欢
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    相关资源
    最近更新 更多