How To: Passing curried functions around

Bahman Movaqar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Sep 6 12:05:31 PDT 2015


I'm just learning D, so please bear with me if I'm asking 
something naive.

Consider the following code skeleton:

     // in part A of the application...
     // 
-------------------------------------------------------------
     alias bool function(int n) validator_t;
     bool isEven(int n) { ... }
     bool isPrime(int n) { ... }
     /**
      * keeps asking for an int from the user until it passes
      * the given validator.
      */
     int readInt(string prompt, validator_t validator) { ... }

     // in part B of the application which knows nothing about 
part A
     // 
-------------------------------------------------------------
     /**
      * does something that involves reading an integer from input
      */
     void foo(intReader_t reader) { ... }

I'm trying to pass curried versions of `readInt` to `foo`.
Obviously, I don't wish part B to know about the details of a 
"reader" nor I'd like to pass `prompt` and `validator` to `foo` 
(this really doesn't concern `foo` at all).

I see that the solution is using `partial` from `std.functional`; 
for example:

     partial!(partial!(readInt, "Enter an integer:"), &isEven)

However, I'm not sure if this is correct (let alone idiomatic!) 
and even if this is the correct way of currying `readInt`, what 
should be the signature of `foo`?

I'd appreciate any help/hint on this.



More information about the Digitalmars-d-learn mailing list