Partial function application: Difference between revisions
Content added Content deleted
m (Added placeholder for LFE) |
(→{{header|LFE}}: Added LFE implementation) |
||
Line 948: | Line 948: | ||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
There is no partial in Erlang, so in LFE we use a closure. |
|||
Here is the code, made more general to account for different arrities (note that to copy and paste into the LFE REPL, you'll need to leave out the docstring): |
|||
<lang lisp> |
<lang lisp> |
||
(defun partial |
|||
"The partial function is arity 2 where the first parameter must be a |
|||
function and the second parameter may either be a single item or a list of |
|||
items. |
|||
When funcall is called against the result of the partial call, a second |
|||
parameter is applied to the partial function. This parameter too may be |
|||
either a single item or a list of items." |
|||
((func args-1) (when (is_list args-1)) |
|||
(match-lambda |
|||
((args-2) (when (is_list args-2)) |
|||
(apply func (++ args-1 args-2))) |
|||
((arg-2) |
|||
(apply func (++ args-1 `(,arg-2)))))) |
|||
((func arg-1) |
|||
(match-lambda |
|||
((args-2) (when (is_list args-2)) |
|||
(apply func (++ `(,arg-1) args-2))) |
|||
((arg-2) |
|||
(funcall func arg-1 arg-2))))) |
|||
</lang> |
|||
Here is the problem set: |
|||
<lang lisp> |
|||
(defun fs (f s) (lists:map f s)) |
|||
(defun f1 (i) (* i 2)) |
|||
(defun f2 (i) (math:pow i 2)) |
|||
(set fsf1 (partial #'fs/2 #'f1/1)) |
|||
(set fsf2 (partial #'fs/2 #'f2/1)) |
|||
(set seq1 '((0 1 2 3))) |
|||
(set seq2 '((2 4 6 8))) |
|||
> (funcall fsf1 seq1) |
|||
(0 2 4 6) |
|||
> (funcall fsf2 seq1) |
|||
(0.0 1.0 4.0 9.0) |
|||
> (funcall fsf1 seq2) |
|||
(4 8 12 16) |
|||
> (funcall fsf2 seq2) |
|||
(4.0 16.0 36.0 64.0) |
|||
</lang> |
</lang> |