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?

4
  • 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 3, 2017 at 8: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 3, 2017 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 3, 2017 at 18:44
  • 1
    Scheme, Racket, Clojure. Alternatively one of the strongly typed functional languages like Haskell, Ocaml, F#.
    – wasamasa
    May 3, 2017 at 20:46

1 Answer 1

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")
1
  • 1
    You can do this to avoid using funcall: (fset 'f (double-the-function 'reverse)) (f "abc") May 7, 2017 at 22:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.