1. Pointer to function in Euphoria

Hi All, just coming to Euphoria planet and I am playing with it. I have this small example in C:

#include <stdio.h> 
#include <stdlib.h> 
 
double f(double x) 
{ 
  return x*x; 
}; 
 
double g(double x) 
{ 
  return 2*x; 
}; 
 
double h(double x) 
{ 
  return x*x*x; 
}; 
 
typedef double (*fp)(double); // Function pointer 
 
double doit(fp f, double a, double b) 
{ 
  return (*f)(a) + (*f)(b); 
} 
 
int main() 
{ 
    double y; 
    y = doit(&f, 3.14159, 2.71828); 
    printf( "y1 = %f\n", y); 
    y = doit(&g, 1.0,2.0); 
    printf( "y2 = %f\n", y); 
    y = doit(&h, 3.0,4.0); 
    printf( "y3 = %f\n", y); 
 
    return 0; 
} 

translated in Lua:

#!/usr/local/bin/lua 
 
function f(x) 
  return x*x 
end 
 
function g(x) 
  return 2*x 
end 
 
function h(x) 
  return x*x*x 
end 
 
 
function doit(f, a, b) 
 
  return f(a) + f(b) 
end 
 
sf=string.format 
y = doit(f,3.14159,2.71828) 
st = string.format("y1 = %f\n", y) 
print(st) 
y = doit(g, 1, 2) 
st = string.format("y2 = %f\n", y) 
print(st) 
y = doit(h,3,4) 
st = string.format("y3 = %f\n", y) 
print(st) 

How do you translate it in Euphoria? Thank You smile

Edit: Use three curly brackets {{{ and }}} to enclose non-Euphoria code or fixed-width content. -Greg

new topic     » topic index » view message » categorize

2. Re: Pointer to function in Euphoria

 
function f(atom x) return x*x end function 
integer fid = routine_id("f") 
 
function g(atom x) return 2*x end function 
integer gid = routine_id("g") 
 
function h(atom x) return x*x*x end function 
integer hid = routine_id("h") 
 
function doit(integer func, atom a, atom b)  
   return call_func(func, {a}) + call_func(func, {b}) 
end function 
 
atom y  
 
y = doit(fid, 3.14159, 2.71828) 
printf(1, "y1 = %f\n", y) 
 
y = doit(gid, 1, 2) 
printf(1, "y2 = %f\n", y) 
 
y = doit(hid, 3, 4) 
printf(1, "y3 = %f\n", y) 
 
new topic     » goto parent     » topic index » view message » categorize

3. Re: Pointer to function in Euphoria

Great! Thank you smile

new topic     » goto parent     » topic index » view message » categorize

Search



Quick Links

User menu

Not signed in.

Misc Menu