如何创建像球拍一样的咖喱功能 [英] How to create a make-curry function like racket has

查看:60
本文介绍了如何创建像球拍一样的咖喱功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想看看如何模拟 racket 提供的 (curry func).这是我如何手动柯里化函数的示例:

I would like to see how it might be possible to emulate the (curry func) that racket provides. Here is an example of how I'm manually currying a function:

#lang sicp
; convert to a curried function

(define (add1 x y) (+ x y))

(define add2
  (lambda (x)
    (lambda (y)
      (+ x y))))

(add1 2 3)
; 5

((add2 2) 3)
; 5

我从哪里开始添加高阶函数,以便将普通"函数转换为柯里化函数,如下所示:

Where would I start to add a higher-order function such that it converts a 'normal' function into a curried function, something like this:

(((curry add1) 2) 3)

推荐答案

您必须进行一些权衡,因为判断一个函数接受多少个参数并不容易.Racket 有一个 procedure-arity 函数,它让 curry 告诉有多少个参数要 curry,但 SICP 语言没有.所以你必须选择如何处理这个问题.一些合理的选择包括:

You have to make some tradeoffs because it's not easy to tell how many parameters a function accepts. Racket has a procedure-arity function that lets curry tell how many arguments to curry, but the SICP language does not. So you have to choose how to handle this. Some reasonable choices include:

  • 让调用者指定等待多少个参数
  • 仅使用固定数量的参数
  • 只对函数进行前 n 次调用,并通过底层函数进行 n+1 次调用.
  • Make the caller specify how many arguments to wait for
  • Work only with a fixed number of arguments
  • Curry only the first n calls to a function, and have the n+1th call through the underlying function.

这篇关于如何创建像球拍一样的咖喱功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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