Nesting level too deep when looping through matrix blocks
element.type is not a simple string (add {{dump(element.type)}} to your loop to see this). What you should use is element.type.handle. So the assignment is:

{% set prevElementType = element.type.handle %}


And the comparison (now of two strings, so no recursion) is:

element.type.handle == prevElementType