Added call to mod(x, m) and replaces isInstanceOf/asInstanceOf by pattern matching