scheme - 如何在 Racket/Plait 中给出特定类型的函数作为参数?

标签 scheme racket plai

我正在编写一个函数,它接受一个函数和一个列表作为参数。参数函数和列表必须具有相同类型的值。我如何确保这一点?

我已经尝试过:

(define ( (func -> 'a) [lst : (Typeof 'a)])
     ....)

但是,我还没能让它工作。我也浏览了辫子教程,但没有找到任何相关内容。

是否有可能有一个函数接受特定返回类型的函数?

最佳答案

这是您要找的吗?

(define f : (('a -> 'a) (listof 'a) -> string)
  (lambda (func lst) "hello"))

然后:

(f (lambda ([x : number]) x) (list 1))

类型检查,但是:

(f (lambda ([x : number]) x) (list "foo"))

不进行类型检查,因为'a与字符串统一(来自"foo"),但也与数字统一(来自x),因此会发生类型不匹配。

请注意

(define f : (('a -> 'a) (listof 'a) -> string)
  (lambda (func lst) "hello"))

(define (f [func : ('a -> 'a)] [lst : (listof 'a)]) : string
  "hello")

不同。在前者中,'a 指的是跨参数的相同类型变量。后者中,func'alst'a是不同的。因此,在后者中,以下表达式类型检查:

(f (lambda ([x : number]) x) (list "foo"))

关于scheme - 如何在 Racket/Plait 中给出特定类型的函数作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54358167/

相关文章:

hashtable - Racket:在 hasheq 错误中找不到键值

scheme - 用 Lisp 编写形式语言解析器

scheme - 如何解决此错误 "reference to an identifier before its definition: with"

scheme - Racket - lang plai - 定义类型和类型案例解释

lisp - 来自 "Realm of Racket"的奇怪代码示例

list - 方案 - 列表的子集

scheme - Lisp中'quote的含义

scheme - 方案中的 curry

racket - scribble/acmart 中的页码