Partial function application: Difference between revisions

Line 1,298:
=={{header|TXR}}==
 
Partial application is built in via the <code>op</code> operator, so there is no need to create all these named functions, which defeats the purpose and beauty of partial application.
The <code>f1</code> function is just <code>mapcar</code>, or at least the oft-used special case thereof when there is only one list to process and the function takes one argument.
 
Indeed, functional language purists would probably say that even the explicit <code>op</code> operator spoils it, somewhat.
The <code>op</code> operator in TXR Lisp is used for partial application.
 
<lang sh>$ txr -p "(mapcar (op mapcar (op * 2)) (list (range 1 3) (range 2 6 2)))"
Multiply every element of a list by two, by partially applying <code>2</code> to the <code>*</code> operator:
((2 4 6) (4 8 12))
 
<lang$ txr> -p "(mapcar (op mapcar (op * 2@1 @1)) '(list (range 1 3) (range 2 36 2)))</lang>"
((1 4 9) (4 16 36))</lang>
 
Now, without further ado, we murder the concept of partial application to meet the task requirements:
Now that is not a function, but a function call. If we want a one-argument function in which the <code>mapcar</code> function itself is curried, we use <code>op</code> again:
 
<lang txrsh>(op$ mapcartxr -e "(op * 2))</lang>progn
(defun fs (fun seq) (mapcar fun seq))
(defun f1 (num) (* 2 num))
(defun f2 (num) (* num num))
(defvar fsf1 (op fs f1)) ;; pointless: can just be (defun fsf1 (seq) (fs f1 seq)) !!!
(defvar fsf2 (op fs f2))
 
(print [fs fsf1 '((1 2 3) (2 4 6))]) (put-line \"\")
This could be applied to the list like this to produce <code>(2 4 6)</code>:
(print [fs fsf2 '((1 2 3) (2 4 6))]) (put-line \"\"))"
 
((2 4 6) (4 8 12))
<lang txr>[(op mapcar (op * 2)) '(1 2 3)]</lang>
((1 4 9) (4 16 36))</lang>
 
We could define names for these functions like the problem statement says, but that defeats much of the point of partial application, which is to construct new functions anonymously, on the fly, in the middle of expressions. When we "farm out" the logic to a named function, we can dispense with some or perhaps all of the partial application.
 
<lang txr>(defun fsf1 (list)
[(op mapcar (op * 2)) list]) ;; pointless complication of just (mapcar (op * 2) list) !</lang>
 
Moreover, if we had a named function <code>f1</code> which does <code>(op * 2)</code> we would just dispense with that partial evaluation also and just write <code>[mapcar f1 list]</code>.
 
Here is an <code>op</code> expression that returns a function which squares the elements of a sequence, producing a new sequence. Since we use the multiplication function, we must repeat an argument and so we must use the <code>@number</code> syntax supported by <code>op</code>:
 
<lang txr>(op mapcar (op * @1 @1))</lang>
 
This is an anonymous version of <code>fsf2</code>.
 
{{omit from|Euphoria}}
543

edits