方案 - 可选参数和默认值 [英] Scheme - Optional arguments and default values

查看:33
本文介绍了方案 - 可选参数和默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently looking into Scheme, and the way I have understood it, procedures can take an arbitrary number of arguments.

我一直在尝试解决这个问题,但我很难理解这个概念.

I have been trying to play around with this, but I'm struggling to grasp the concept.

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

For instance, say I want to write a welcome message, based on information provided by the user.

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

If user provides a first and last name, the program shout write:

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

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

Otherwise, the program should refer to a default value, specified as:

Welcome, Anonymous Person!

我的代码有以下大纲,但正在苦苦思索如何完成.

I have the following outline for my code, but struggling with how to finalise this.

(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!

非常感谢任何帮助!

推荐答案

在 Racket 中,这样做的方法是使用 关键字参数.你可以定义一个带有关键字参数的函数,我在声明参数时写#:keyword argument-id:

In Racket, the way to do this would be using keyword arguments. You can define a function with keyword arguments my writing #:keyword argument-id when declaring the arguments:

(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].

However, what you want is to make them optional. To do that, you can write #:keyword [argument-id default-value] in the argument declaration.

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

这样,如果您在某个函数调用中不使用该关键字,则使用默认值填充.

So that if you don't use that keyword in a certain function call, it is filled with the default value.

> (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!

这篇关于方案 - 可选参数和默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆