Skip to content

Preprocess elseif constructs correctly #53

@Schlevidon

Description

@Schlevidon

Summary

IFDIFF can currently only correctly preprocess if-constructs of the form

if condition
	if_part...
else
	else_part...
end

We would also like to allow usage of the elseif keyword, i.e.

if condition
	if_part...
elseif condition
	elseif_part...
else
	else_part...
end

Possible Solution

Main Idea

The simplest approach would be to transform elseif blocks into separate if-else blocks (which can then be preprocessed by IFDIFF as usual), i.e.

if condition
	if_part...
elseif condition
	elseif_part...
else
	else_part...
end

would become

if condition
	if_part...
else
	if condition
		elseif_part...
	else
		else_part...
	end
end

However, one would also need to handle multiple elseif blocks correctly, i.e.

if condition
	if_part...
elseif condition
	elseif_part1...
elseif condition
	elseif_part2...
else
	else_part...
end

becomes

if condition
	if_part...
else
	if condition
		elseif_part1...
	else
		if condition
			elseif_part2...
		else
			else_part...
		end
	end
end

This can probably be handled by simply correctly applying the single elseif transformation to each elseif in the code in order of appearance, i.e.

if condition
	if_part...
elseif condition
	elseif_part1...
elseif condition
	elseif_part2...
else
	else_part...
end

first becomes

if condition
	if_part...
else
	if condition
		elseif_part1...
	elseif condition
		elseif_part2...
	else
		else_part...
	end
end

and then becomes

if condition
	if_part...
else
	if condition
		elseif_part1...
	else
		if condition
			elseif_part2...
		else
			else_part...
		end
	end
end

Edge Cases

Keep in mind that elseif and else parts are optional.

Examples

The canonical example RHS

function dx = canonicalExampleRHS(t,x,p)

dx = zeros(2,1);
dx(1) = 0.01 * t.^2  +  x(2).^3;

if x(1) < p(1) 
    dx(2) = 0;
else
    if x(1) < p(1) + 0.5
        dx(2) = 5;
    else
        dx(2) = 0;
    end
end
end

can be rewritten with elseif as

function dx = canonicalExampleRHS(t,x,p)

dx = zeros(2,1);
dx(1) = 0.01 * t.^2  +  x(2).^3;

if x(1) < p(1) 
    dx(2) = 0;
elseif x(1) < p(1) + 0.5
      dx(2) = 5;
else
      dx(2) = 0;
end
end

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions