## How do I assign functions from expressions in Maple?

Maple

Maple users frequently solve differential equations. If you want to use the results later in Maple, you need to deconstruct the solution, and then assign the functions -- something that isn't done automatically in Maple. We wrote a multi-purpose routine to help you out. For instance, suppose you solve a simple linear system of equations:

```restart;

eqs := { x + y = 3, x - y = 1 };
soln := solve( eqs ); # { x = 2, y = 1 }
x, y; # plain x and y```

To assign the values from the solution to the corresponding variables:

```assign( soln );
x, y; # 2, 1```

This won't work for solutions of differential equations:

```restart;

sys := { D(x)(t) = y(t), D(y)(t) = -x(t), x(0) = 1, y(0) = 0 };
soln := dsolve( sys ); # { x(t) = cos(t), y(t) = -sin(t) }
assign( soln );
x(s), y(s); # plain x(s) and y(s)```

To make this work, we wrote this multi-purpose routine:

```restart;

# Type for a variable expression, e.g. x=5.
TypeTools:-AddType( 'varexpr', u -> type( u, 'And'('name','Non'('constant'))='algebraic' ) ):

# Type for a function expression, e.g. f(x)=x^2.
TypeTools:-AddType( 'funcexpr', u -> type( u, 'function'('And'('name','Non'('constant')))='algebraic' ) ):

# Procedure to assign variable and function expressions.
my_assign := proc( u :: {
varexpr, 'list'(varexpr), 'rtable'(varexpr), 'set'(varexpr),
funcexpr, 'list'(funcexpr), 'rtable'(funcexpr), 'set'(funcexpr)
}, \$ )

local F, L, R, V:

# Map the procedure if input is a data container, or apply regular assign(), where applicable.
if not u :: {'varexpr','funcexpr'} then
map( procname, u ):
return NULL:
elif u :: 'varexpr' then
assign( u ):
return NULL:
end if:

L, R := lhs(u), rhs(u):
F := op(0,L):
V := [ indets( L, 'And'( 'name', 'Non'('constant') ) )[] ]:

map( assign, F, unapply( R, V ) ):
return NULL:

end proc:

# Example 1.

eqs := { x + y = 3, x - y = 1 };
my_assign( solve( eqs ) );
'x' = x, 'y' = y; # x=1, y=2

# Example 2.

unassign( 'x', 'y' ):
E := [ f(x,y) = x + y, g(x,y) = x - y ];
my_assign( E );
'f(u,v)' = f(u,v), 'g(u,v)' = g(u,v); # f(u,v)=u+v, g(u,v)=u-v

# Example 3.

sys := { D(x)(t) = y(t), D(y)(t) = -x(t), x(0) = 1, y(0) = 0 };
soln := dsolve( sys );
my_assign( soln ):
'x(s)' = x(s); # x(s)=cos(s)
'y(s)' = y(s); # y(s)=-sin(s)```

﻿