Generic implementation of beta reduction