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

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

问题描述

我目前正在研究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!

我们非常感谢您的帮助!

Any help is highly appreciated!

推荐答案

在Racket中,使用

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天全站免登陆