Skip to main content
gamedev.net
🔒 Locked

Function Tree ?

Started by Endemoniada 2 replies 350+ views
Original Post
Endemoniada
Endemoniada
Hi guys, How would I go about programming something like this: z=f(input); where input can be a scaler or a function just like f. So I could end up with something like this: z=f(g(h(input))); It's for genetic textures so I don't know how many functions there will be. It's weird because I have to go from the inside out. That's just a single input/single output example but if I can get the hang of that I can do more advanced things like: z=f(g(h(input1,input2),input3)); I'm pretty sure it falls under trees and I don't know much about them yet, I will read some tutorials but I thought someone here could give me a general direction. Thank you.
Zipster
Zipster
Sounds like a job for expression templates to me. Aren't they just the cat's meow these days?
stylin
stylin
Quote:
Original post by Zipster
Sounds like a job for expression templates to me. Aren't they just the cat's meow these days?

Your layout seems pretty straightforward to me. All of your functions are just returning scalars. Why can't you just use normal functions?
   typedef float scalar;   // functions that do something with scalars   scalar f( scalar k ) { return result; }   scalar g( scalar k1, scalar k2 ) { return result; }   scalar h( scalar k1, scalar k2 ) { return result; }   ...   scalar k = f( g( h( 420, 69 ), 420.69 ) );

Sorry if I've misunderstood your problem.
:stylin: "Make games, not war." "...if you're doing this to learn then just study a modern C++ compiler's implementation." -snk_kid
ToohrVyk
ToohrVyk
You can create a simple tree structure, with evaluation scheme, using the following method (OCaml source):

exception ArityErrortype arityFunction = (float array -> float)let makeArity (f) (arity) =   let func (a) = if Array.length a <> arity then raise ArityError else (f a)  in functype tree = Leaf of float | Node of arityFunction * (tree array)let rec eval = function  | Node (f,a) = f (Array.map eval a)  | Leaf s -> s


Then, to represent the expression:
z = f( g( 10, 20 ), 30 ), with g(x,y) = x + y and f(x,y) = x*y
You would use the code:

let f a = a.(0) *. a.(1);;let g a = a.(0) +. a.(1);;let z =   Node ((makeArity f 2),    [| Node ((makeArity g 2), [| Leaf 10.; Leaf 20. |]); Leaf 30; |] );;let value = eval z;;

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.