define a form as function name?

江枫思渺然 提交于 2019-12-10 20:38:13

问题


I'd like to know what this code means in Scheme:

(define ((K x) y) x)

(define (((S x) y) z)
  ((x z) (y z)))

The whole file is here.

Is this legal Scheme? Is (K x) a parametrized function, something like generic functions in Java? I looked up the MIT Scheme reference, there seems to be nothing mentioned for definition of this kind.


回答1:


Trying it in MIT Scheme works

(define ((K x) y) x)
;Value: k

((k 3) 4)
;Value: 3

Apparently, these are the definitions for K and S combinators from a combinatorial logic SKI calculus.

We can define the same function explicitly,

(define k (lambda (x) (lambda (y) x)))
;Value: k

((k 3) 4)
;Value: 3

Apparently, MIT-Scheme does that for us, just as in case of regular definitions like (define (fun foo) bar) being translated to (define fun (lambda (foo) bar)).

The S combinator would be defined explicitly as

(define S (lambda (x) (lambda (y) (lambda (z) 
  ((x z) (y z))))))

(define ((add a) b) (+ a b))
;Value: add

(define (add1 a) (+ a 1))
;Value: add1

(((s add) add1) 3)
;Value: 7

This is how currying languages (like e.g. Haskell) work, where every function is a function of one argument. Haskell is very close to the combinatorial logic in that respect, there's no parentheses used at all, and we can write the same definitions simply as

_K x y = x
_S x y z = x z (y z)

So that _S (+) (1+) 3 produces 7.




回答2:


It's called Curried Function Shorthand and described here.



来源:https://stackoverflow.com/questions/19584596/define-a-form-as-function-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!