1

I'd like to write an elisp-function that has a function as argument and returns a new function.

Let's say the new function double-the-function should write the returned value of the argument-function twice. (The argument function operates on a string and returns a string. This is ensured.)

So:

(reverse "abc") returns: "cba"

If I define the function f as follows:

(setq f (double-the-function reverse))

I expect that:

(f "abc") returns "cbacba"

which is equal to (concat (reverse cba) (reverse "cba")).

How to define double-the-function?

Drew
  • 75,699
  • 9
  • 109
  • 225
rl1
  • 346
  • 1
  • 16
  • 1
    If you *quote* the function symbol (i.e. `'reverse` ) when you pass it as an argument, then `double-the-function` can simply use `funcall` to call its argument as a function. With this information, you can probably answer your own question. – phils May 03 '17 at 08:48
  • Keep in mind that elisp is one of the worse languages to do FP in. While you can with some contortions, that's not what idiomatic code looks like. – wasamasa May 03 '17 at 17:26
  • @wasamasa Which langugage would you suggest? Most of the time I'm working with emacs that's why I have chosen elisp. I don't have to configure anything: I just open an .el-file and can code and test the code in the file itself. That's very easy for me. – rl1 May 03 '17 at 18:44
  • 1
    Scheme, Racket, Clojure. Alternatively one of the strongly typed functional languages like Haskell, Ocaml, F#. – wasamasa May 03 '17 at 20:46

1 Answers1

1
;; -*- lexical-binding : t -*-
(defun double-the-function (fn)
  (lambda (string)
    (let ((result (funcall fn string)))
      (concat result result))))

(funcall (double-the-function 'reverse) "abc")
politza
  • 3,316
  • 14
  • 16