示例#1
0
string Pi::toString(){
	string str;
	if (this->coefficient->getType() != "Integer"){
		str += this->coefficient->toString();
	}
	else{
		Integer* co = dynamic_cast<Integer*>(this->coefficient);
		if (co->getValue() != 1){
			str += this->coefficient->toString();
		}
		else{

		}
	}
	if (this->exponent->getType() == "Integer"){
		Integer* exp = dynamic_cast<Integer*>(this->exponent);
		if (exp->getValue() == 0){
			return str;
		}
		else if (exp->getValue() == 1){
			str += "pi";
			return str;
		}

	}
	else{
		str += "(pi^";
		str += this->exponent->toString();
		str += ")";
		return str;
	}
}
// TileMapAtlas - Atlas generation / updates
void TileMapAtlas::setTile(const Color3B& tile, const Point& position)
{
    CCASSERT(_TGAInfo != NULL, "tgaInfo must not be nil");
    CCASSERT(_posToAtlasIndex != NULL, "posToAtlasIndex must not be nil");
    CCASSERT(position.x < _TGAInfo->width, "Invalid position.x");
    CCASSERT(position.y < _TGAInfo->height, "Invalid position.x");
    CCASSERT(tile.r != 0, "R component must be non 0");

    Color3B *ptr = (Color3B*)_TGAInfo->imageData;
    Color3B value = ptr[(unsigned int)(position.x + position.y * _TGAInfo->width)];
    if( value.r == 0 )
    {
        CCLOG("cocos2d: Value.r must be non 0.");
    } 
    else
    {
        ptr[(unsigned int)(position.x + position.y * _TGAInfo->width)] = tile;

        // XXX: this method consumes a lot of memory
        // XXX: a tree of something like that shall be implemented
        Integer *num = (Integer*)_posToAtlasIndex->objectForKey(String::createWithFormat("%ld,%ld", 
                                                                                                 (long)position.x, 
                                                                                                 (long)position.y)->getCString());
        this->updateAtlasValueAt(position, tile, num->getValue());
    }    
}
示例#3
0
bool Integer::operator!=(Numeric* c)const{
  Integer* entier = dynamic_cast<Integer*>(c);
  if(entier==NULL){
     return false;
  }
  return (_value != entier->getValue());
}
示例#4
0
Numeric* Integer::operator /(Numeric* c)const{
    Integer* entier = dynamic_cast<Integer *>(c);
    if(entier==NULL)
    {
        Real* reel=dynamic_cast<Real*>(c);
        if(reel==NULL){
            Rational *rationnel=dynamic_cast<Rational *>(c);
            Rational *result=new Rational(Integer(_value*rationnel->getDenominator().getValue()),Integer(rationnel->getNumerator().getValue()));
            result->simplification();
            if(result->getDenominator().getValue()==1 || result->getNumerator().getValue()==0){
                Integer* resE = new Integer(result->getNumerator().getValue());
                delete result;
                return resE;
            }
            return result;
        }
        if(reel->getValue() ==0)
            throw QString("Can't divide by 0 !");
        return new Real(((double)_value)/reel->getValue());
    }
    if(entier->getValue() ==0)
        throw QString("Can't divide by 0 !");
    Rational* res = new Rational(*this,*entier);
    res->simplification();
    if(res->getDenominator().getValue()==1 || res->getNumerator().getValue()==0){
        Integer* resE = new Integer(res->getNumerator().getValue());
        delete res;
        return resE;
    }
    return res;
}
TEST( Int02, Integers )
{
    Integer i;
    IntType expected = 0;
    IntType actual = i.getValue();
    CHECK_EQUAL( expected, actual )
}
示例#6
0
//main function
int main(int argc, char* argv[]) {
	puts("Under construction!");
	puts("Please pardon our mess!");
	puts("Currently testing Integer objects.");
	Integer* intOne = createInteger("intOne", 3, false);
	Integer* constInt = createInteger("constInt", 4, true);
	printf("Before changing, the value of %s is %d.\n", intOne->getName(intOne), intOne->getValue(intOne));
	printf("Before changing, the value of %s is %d.\n", constInt->getName(constInt), constInt->getValue(constInt));
	intOne->setValue(intOne, 5);
	constInt->setValue(constInt, 6);
	printf("After changing, the value of %s is %d.\n", intOne->getName(intOne), intOne->getValue(intOne));
	printf("After changing, the value of %s is %d.\n", constInt->getName(constInt), constInt->getValue(constInt));
	destroyInteger(intOne);
	destroyInteger(constInt);
	return EXIT_NO_ERR;
}
void EGLViewProtocol::getSetOfTouchesEndOrCancel(Set& set, int num, int ids[], float xs[], float ys[])
{
    for (int i = 0; i < num; ++i)
    {
        int id = ids[i];
        float x = xs[i];
        float y = ys[i];

        Integer* pIndex = (Integer*)s_TouchesIntergerDict.objectForKey(id);
        if (pIndex == NULL)
        {
            CCLOG("if the index doesn't exist, it is an error");
            continue;
        }
        /* Add to the set to send to the director */
        Touch* pTouch = s_pTouches[pIndex->getValue()];        
        if (pTouch)
        {
            CCLOGINFO("Ending touches with id: %d, x=%f, y=%f", id, x, y);
			pTouch->setTouchInfo(pIndex->getValue(), (x - _viewPortRect.origin.x) / _scaleX, 
								(y - _viewPortRect.origin.y) / _scaleY);

            set.addObject(pTouch);

            // release the object
            pTouch->release();
            s_pTouches[pIndex->getValue()] = NULL;
            removeUsedIndexBit(pIndex->getValue());

            s_TouchesIntergerDict.removeObjectForKey(id);

        } 
        else
        {
            CCLOG("Ending touches with id: %d error", id);
            return;
        } 

    }

    if (set.count() == 0)
    {
        CCLOG("touchesEnded or touchesCancel: count = 0");
        return;
    }
}
TEST( Int03, Integers )
{
    Integer i;
    i.setValue( 51 );
    IntType expected = 51;
    IntType actual = i.getValue();
    CHECK_EQUAL( expected, actual )
}
示例#9
0
NS_CC_BEGIN

static std::vector<unsigned int> ccarray_to_std_vector(Array* pArray)
{
    std::vector<unsigned int> ret;
    Object* pObj;
    CCARRAY_FOREACH(pArray, pObj)
    {
        Integer* pInteger = (Integer*)pObj;
        ret.push_back((unsigned int)pInteger->getValue());
    }
示例#10
0
int getInt(Atom *a)
{
	Integer *i = dynamic_cast<Integer*>(a);

#ifdef _DEBUG
	if (i == 0) {
		throw std::exception("Integer以外の型を変換しようとしました");
	}
#endif
	return i->getValue();
}
// Redefinición del método Object::equals para poder comparar dos Integers
bool Integer::equals(Object* other)const{
    // Se revisa que el parámentro no sea NULL
    if (other == NULL)
        return false;
    // Se verifica que el parámetro sea de tipo Integer
    if (dynamic_cast<Integer*>(other) == NULL) // No son del mismo tipo
        return false; // Retornar false en el caso de que sea de otro tipo
    // Se convierte el parámetro a Integer para tener acceso a value
    Integer* tempInteger = dynamic_cast<Integer*>(other);
    // Se comparan los valores para verificar igualdad
    return tempInteger->getValue() == value;
}
void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[])
{
    Set set;
    for (int i = 0; i < num; ++i)
    {
        int id = ids[i];
        float x = xs[i];
        float y = ys[i];

        Integer* pIndex = (Integer*)s_TouchesIntergerDict.objectForKey(id);
        if (pIndex == NULL) {
            CCLOG("if the index doesn't exist, it is an error");
            continue;
        }

        CCLOGINFO("Moving touches with id: %d, x=%f, y=%f", id, x, y);
        Touch* pTouch = s_pTouches[pIndex->getValue()];
        if (pTouch)
        {
			pTouch->setTouchInfo(pIndex->getValue(), (x - _viewPortRect.origin.x) / _scaleX, 
								(y - _viewPortRect.origin.y) / _scaleY);
            
            set.addObject(pTouch);
        }
        else
        {
            // It is error, should return.
            CCLOG("Moving touches with id: %d error", id);
            return;
        }
    }

    if (set.count() == 0)
    {
        CCLOG("touchesMoved: count = 0");
        return;
    }

    _delegate->touchesMoved(&set, NULL);
}
示例#13
0
Numeric* Integer::pow(Numeric* c)const{
    Integer* entier = dynamic_cast<Integer *>(c);
    if(entier==NULL){
        Real* reel=dynamic_cast<Real*>(c);
        if(reel==NULL){
            Rational *rationnel=dynamic_cast<Rational *>(c);

            return new Real(std::pow(_value,rationnel->toDouble()));
        }
        return new Real(std::pow(_value,reel->getValue()));
    }
    return new Integer(std::pow(_value,entier->getValue()));
}
	static void Test001(TestUnit *tu)
	{
		tu->runTestCase(__FUNCTION__);
		
		StringSeparator ss("500");
		Atom *a = ListGenerator::generate(ss);

		tu->assertTrue(a->getType() == "Integer", __LINE__);

		Integer *it = dynamic_cast<Integer*>(a);
		tu->assertTrue(it->getValue() == 500, __LINE__);
		return ;
	}
示例#15
0
int Permutation::next()
{
    if (r == 0) return -1;

    int rand = random->getRandomInt(1, numbers->size());
    Integer* num = numbers->get(rand);
    int value = num->getValue();
    numbers->remove(rand);
    delete num;
    r--;

    return value;
}
void Exponential::exponentiate(){
	Integer* one = new Integer(1);
        Rational* oneRat = new Rational(1, 1);
	if (this->base->type == "rational") {
		Rational* ratBase = (Rational *) this->base;
		Exponential* numAsExponential = new Exponential ((ratBase->geteNumerator()), (this->exponent));  //no matching constructor for exponential
		Exponential* denAsExponential = new Exponential ((ratBase->geteDenominator()), (this->exponent));    //same error
		Rational* newRatBase = new Rational(numAsExponential, denAsExponential);
		this->base = newRatBase;
		this->exponent = oneRat;
	}
	else {

    if (this->exponent->getNumerator()==0) {
        
       this->exponent=oneRat;
       this->base=one;

    }
    bool toFlip = false;
    if (exnu->getValue()<0) {
	    exnu->setValue(exnu->getValue()*-1);
            toFlip = true;
            //handles negative exponents
    }
    Expression* constantBase = 0;
    if (base->type == "integer") {              //fixed the problem for integers but nothing else
        Integer *a = (Integer *)base;
        constantBase = new Integer(a->getValue());
    }


    while (exponent->getNumerator()>1)
    	{
        base->multiply(constantBase);
        exponent->setNumerator(exponent->geteNumerator()->subtract(one));
    }
    if (toFlip) {
        while (exnu->getValue() > 1) {
            base->multiply(constantBase);
            exnu->subtract(one);
        }
        Integer* one = new Integer(1);
        Rational* mouse = new Rational(one, base);
    	base = mouse;
        exponent = new Rational(1,1);
    }
    
	}

}
示例#17
0
bool Integer::operator>(Numeric* c)const{
  Integer* entier = dynamic_cast<Integer*>(c);
  if(entier==NULL){
    Real* reel = dynamic_cast<Real*>(c);
    if (reel == NULL){
      Rational* rationnel = dynamic_cast<Rational*>(c);
      if (rationnel == NULL)
        return false;
      return ((double)_value > rationnel->toDouble());
    }
    return ((double)_value > reel->getValue());
  }
  return (_value > entier->getValue());
}
示例#18
0
Numeric* Integer::operator+(Numeric* c)const{
    Integer* entier = dynamic_cast<Integer *>(c);
    if(entier==NULL){
        Real* reel=dynamic_cast<Real*>(c);
        if(reel==NULL){
            Rational *rationnel=dynamic_cast<Rational *>(c);
            Rational *result=new Rational(Integer(_value*rationnel->getDenominator().getValue()-rationnel->getNumerator().getValue()),Integer(rationnel->getDenominator().getValue()));
            result->simplification();
            return result;
        }
        return new Real(((double)_value)+reel->getValue());
    }
    return new Integer(_value+entier->getValue());
}
	static void Test002(TestUnit *tu)
	{
		tu->runTestCase(__FUNCTION__);
		
		Atom *a = Evaluator::eval(
					ListGenerator::generate(
						StringSeparator("(* 1 2 3 5)")
					));

		Integer *result = dynamic_cast<Integer*>(a);

		tu->assertTrue(result->getType() == "Integer", __LINE__);
		tu->assertTrue(result->getValue() == 30, __LINE__);
		return ;
	}
示例#20
0
	static void Test004(TestUnit *tu)
	{
		tu->runTestCase(__FUNCTION__);
		
		Integer i(333);

		Variant *v = new Variant("Test_Object",&i);
		VariantPool &vp = VariantPool::getInstance();
		vp.addVariant(v);

		Atom *a = Evaluator::eval(v);
		tu->assertTrue(a->getType() == "Integer", __LINE__);
		Integer *ret = dynamic_cast<Integer*>(a);
		tu->assertTrue(ret->getValue() == 333, __LINE__);
		return ;
	}
void Expression::simplify(){
	this->coefficent->simplify();
	Number* common = this->expr[1]->getCoefficient();
	int count;
	int opCount;
	for (int j = 0; j < this->expr.size() - 1; j++){
		count = 0;
		opCount = 0;
		Rational* rat = new Rational(common, expr[j]->getCoefficient());
		rat->simplify();
		if (rat->getDenominator()->getType() == "Integer"){
			Integer* den = dynamic_cast<Integer*>(rat->getDenominator());
			if (den->getValue() != 1){
				break;
			}

		}
		else if (rat->getDenominator()->getType() == "Operator"){
			opCount++;
		}
		else{
			count++;
		}
		if (opCount + count == this->expr.size()){
			this->coefficent = common;
			for (int j = 0; j < this->expr.size() - 1; j++){
				Rational* rat = new Rational(this->expr[j]->getCoefficient(), common);
				rat->simplify();
				this->expr[j]->setCoefficient(rat);

			}
		}
	}
	for (int i = 0; i < this->expr.size(); i++){
		if (this->expr[i]->getType() == "Operator"){
			Operator* opera = dynamic_cast<Operator*>(this->expr[i]);
			if (opera->getOperator() == "-"){
				this->expr[i] = new Operator("+");
				Multiply mult = Multiply();
				this->expr[i + 1] = mult.evaluate(this->expr[i + 1], new Integer(-1));
			}
			this->expr[i]->simplify();
		}
	}
}
Exponential::Exponential(Expression* base, Rational* exponent){
    this->type = "exponential";
    this->base = base;
    this->exponent = exponent;
    this->exde = new Integer(exponent->getDenominator());
    if (exde->getValue() != 1) {
    	//if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1
    	Integer* baseAsInteger = (Integer *) base;
        this->base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1);
        Integer* one = new Integer(1);
        this->exponent->setDenominator(one);
    }else{
        this->exnu = new Integer(exponent->getNumerator());
        if (canExponentiate()) {
            exponentiate();
        }
    }
}
示例#23
0
void MySnake::changeRandomSpritePozition()
{
    Array *totalArray = Array::createWithCapacity(col_num * row_num);
    for (int i=0; i<totalArray->capacity(); i++) {
        totalArray->addObject(Integer::create(i));
    }
    
    for (int i=0; i < getChildrenCount()-1; i++) {
        MySprite *sprite = (MySprite *)getChildByTag(i+batchNodeStartTag);
        
        totalArray->removeObjectAtIndex(sprite->getIndex());
    }
    
    int randIndex = (CCRANDOM_0_1()+1) * totalArray->count();
    randIndex = CCRANDOM_0_1() * totalArray->count();
    Integer* pozitionIndex = (Integer *)totalArray->getObjectAtIndex(randIndex);
 
    randomSprite->setIndex(pozitionIndex->getValue());
}
示例#24
0
string NatE::toString(){
	string str = "";
	if (this->coefficient->getType() == "Integer"){
		Integer* co = dynamic_cast<Integer*>(this->coefficient);
		if (co->getValue() == 0){
			str += "0";
			return str;
		}
		else if (co->getValue() == 1){
			if (this->exponent->getType() == "Integer"){
				Integer* exp = dynamic_cast<Integer*>(this->exponent);
				if (exp->getValue() == 0){
					return str;
				}
				else if (exp->getValue() == 1){
					str += "e";
					return str;
				}

			}

				else{
					str += "e^(";
					str += this->exponent->toString();
					str += ")";
					return str;
				}
			}
		else{
			str += this->coefficient->toString();
			if (this->exponent->getType() == "Integer"){
				Integer* exp = dynamic_cast<Integer*>(this->exponent);
				if (exp->getValue() == 0){
					return str;
				}
				else if (exp->getValue() == 1){
					str += "e";
					return str;
				}

			}
			else{
				str += "(e^";
				str += this->exponent->toString();
				str += ")";
				return str;
			}
		}
	}
}
void Complex::mul(Object *b)
{
     if(b->getType() == "Complex")
     {
         Complex *c = (Complex *)b; 
         this->real = (this->real)*(c->getValue1())-(this->imag)*(c->getValue2());
         this->imag = (this->real)*(c->getValue2())+(this->imag)*(c->getValue1()); 
     } 
     else if(b->getType() == "Real") 
     {
          Real *c = (Real *)b;
          this->real *= c->getValue(); 
          this->imag *= c->getValue(); 
     }
     else if(b->getType() == "Rational")
     {
          //Rational->Real 
          Real *c = (Real *)new Real(0.0);//这种垃圾如何回收? 
          Rational *d = (Rational *)b; 
          c->changeValue((double)(d->getValue1())/(d->getValue2()));  
          this->mul(c); //递归 
          delete c;          //这里回收挖~ 
     }
     else if(b->getType() == "Integer")
     {
          //Integer->Rational
          Rational *c = (Rational *)new Rational(0,1);
          Integer *d = (Integer *)b;
          c->changeValue1(d->getValue());
          this->mul(c);  //递归 
          delete c; 
     } 
     else
     {
         cerr << "Error calcution"  << endl; 
     } 
}
示例#26
0
	// range()
	//
	Object *range( Interpreter *interpreter, Scope *scope, List *parameters )
	{

		if( parameters->getLength() != 1 )
		{

			setRuntimeError( ERROR_FUNCTION_TAKES_X_PARAMETERS, "range", 1, parameters->getLength() );
			return 0;
		}

		Object *parameter = parameters->getElementInt( 0 ); // new reference
		Integer *length = dynamic_cast< Integer * >( parameter ); // steals reference
		if ( !length )
		{

            // clean up
            parameter->decRef();

            setRuntimeError( ERROR_PARAMETER_X_MUST_BE_TYPE_Y, "range", 1, "integer" );
			return 0;
		}

		int l = length->getValue();
		List *result = new List( l ); // new reference
		for ( int i = 0; i < l; ++i )
        {

            Integer *element = new Integer( i ); // new reference
			result->setElementInt( i, element ); // takes reference
            element->decRef();
        }

        // clean up
        length->decRef();

		return result;
	}
string Expression::toString(){
	string str = "";
	if (this->coefficent->getType() == "Integer"){
		Integer* co = dynamic_cast<Integer*>(this->coefficent);
		if (co->getValue() != 1){
			str += this->coefficent->toString();
			str += "(";
			for (int i = 0; i < expr.size(); i++){
				str += expr[i]->toString();
			}
			
		}
		else {
			str += "(";
			for (int i = 0; i < expr.size(); i++){
				str += expr[i]->toString();
			}
			
		}
	}
	else{
		str += this->coefficent->toString();
		str += "(";
		for (int i = 0; i < expr.size(); i++){
			str += expr[i]->toString();
		}
	}

	if (this->exponent->getType() == "Integer"){
		Integer* ex = dynamic_cast<Integer*>(this->exponent);
		if (ex->getValue() != 1){
			str += ")";
			str += "^";
			str += this->exponent->toString();
		}
		else{
			str += ")";
		}
	}
	else{
		str += ")";
		str += "^";
		str += this->exponent->toString();

	}
	for (int i = 0; i < str.size(); i++){
		if (str.at(i) == '0'){
			if (str.at(i - 1) == '('){
				str.erase(i, 1);
			}
			else if (str.at(i-1)=='+'){
				str.erase(i - 1, 2);
			}
		}
	}
	for (int i = 0; i < str.size(); i++){
		if (str.at(i) == '+'){
			if (str.at(i - 1) == '('){
				str.erase(i, 1);
			}
		}
	}
	return str;
}
示例#28
0
void		Enemy::checkForAndResolveCollisions()
{


	CCPoint playerPos = getPosition();
	CCArray* tiles = getSurroundingTilesAtPosition(playerPos);
	CCObject* obj;
	_onGround = false;

	bool isSideHit = false;
	CCARRAY_FOREACH(tiles,obj)	
	{
		CCDictionary* dict = (CCDictionary*)obj;



		Integer* x = (Integer*)dict->objectForKey("x");
		Integer* y = (Integer*)dict->objectForKey("y");
		float height = _map->getTileSize().height;
		float width = _map->getTileSize().width;
		//_debugDraw->appendRect(ccp(x->getValue(), y->getValue()), width, height);


		CCRect pRect = collisionBoundingBox();

		//_debugDraw->appendRect(ccp(pRect.getMinX(), pRect.getMinY()), pRect.getMaxX() - pRect.getMinX() , pRect.getMaxY() - pRect.getMinY(), 1.0f, 0.0f, 0.0f);
		Integer* gid = (Integer*)dict->objectForKey("gid");
		if(gid->getValue())
		{

			CCRect tileRect = CCRectMake((float)x->getValue(),(float)y->getValue(), _map->getTileSize().width, _map->getTileSize().height);
	
			if(pRect.intersectsRect(tileRect))
			{

				CCRect intersectRect = pRect.intersectsWithRect(tileRect);	
				int tileIndx = tiles->getIndexOfObject(obj);
				//CCLOG("tileIndx %d : " ,tileIndx);
				if(tileIndx == 0)
				{
					//CCLOG("0 intersect ");
					//_debugDraw->appendRect(ccp(intersectRect.getMinX(), intersectRect.getMinY()), intersectRect.getMaxX() - intersectRect.getMinX() , intersectRect.getMaxY() - intersectRect.getMinY(), 1.0f, 0.0f, 0.0f);
					_onGround = true;
					setVelocity(ccp(getVelocity().x, 0.0f));
					setDesiredPosition(ccp(getDesiredPosition().x, getDesiredPosition().y + intersectRect.size.height));
					//_player->setDesiredPosition(ccp(_player->getDesiredPosition().x, 13));
					//CCLOG("Player box %f", tileRect.getMaxY() - pRect.getMinY());
					//CCLOG("tile box %f", tileRect.getMaxY());
					//CCLOG("intersectRect box %f", intersectRect.size.height);
				}
				else if(tileIndx == 1)
				{
					//CCLOG("1 intersect ");
					
					setDesiredPosition(ccp(getDesiredPosition().x, getDesiredPosition().y - intersectRect.size.height));
				}	
				else if(tileIndx == 2)
				{
					//CCLOG("2 intersect ");
					isSideHit = true;
					setVelocity(ccp(0.0f,getVelocity().y));
					setDesiredPosition(ccp(getDesiredPosition().x  + intersectRect.size.width, getDesiredPosition().y));
				}
				else if(tileIndx == 3)
				{
					//CCLOG("3 intersect ");
					isSideHit = true;
					setVelocity(ccp(0.0f,getVelocity().y));
					setDesiredPosition(ccp(getDesiredPosition().x  - intersectRect.size.width, getDesiredPosition().y));
				}
				else
				{
					if(intersectRect.size.width > intersectRect.size.height)
					{
						float resolutionHeight;
						if(tileIndx > 5)
						{
							resolutionHeight  = intersectRect.size.height;
							setVelocity(ccp(getVelocity().x, 0.0f));
							_onGround = true;
						}
						else
						{
							resolutionHeight  = -intersectRect.size.height;
						}
						setDesiredPosition(ccp(getDesiredPosition().x, getDesiredPosition().y + resolutionHeight ));
					}
					else
					{
						float resolutionWidth;
						if (tileIndx == 6 || tileIndx == 4) 
						{
							resolutionWidth = intersectRect.size.width;
						}
						else
						{
							resolutionWidth = -intersectRect.size.width;
						}
						setDesiredPosition(ccp(getDesiredPosition().x + resolutionWidth, getDesiredPosition().y ));
					}
					//if((tileIndx == 5 || tileIndx == 4) && getVelocity().y > 0 && !isSideHit)

				}
			}
		}

	}
示例#29
0
	Integer(const Integer &rhs){						//copy constructor
		storedValue = rhs.getValue();
	}
示例#30
0
/*** Evaluate this object ***/
Object* SpecialFunction::evaluate()
{
	if(args.size() == 0)
		throw Excep(getLineNumber(), getColumnNumber(), "Expected argument to special function!");

	std::auto_ptr<Object> arg1(args.at(0)->evaluate());

	if(id == SPF_INDEX)
	{
		if(args.size() != 2)
			throw Excep(getLineNumber(), getColumnNumber(), "Invalid number of arguments passed to special function!");

		std::auto_ptr<Object> arg2(args.at(1)->evaluate());

		if(arg2->getType() == OBJ_TEXT)
		{
			if(arg1->getType() != OBJ_TEXT)
				throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_TEXT, arg1->getType(), 1);

			Text* cast1 = static_cast<Text*>(arg1.get());
			Text* cast2 = static_cast<Text*>(arg2.get());

			size_t index = cast2->getValue().find(cast1->getValue());

			if(index != std::string::npos)
				return new Integer(index + 1);

			return new Integer(0);
		}

		if(arg2->getType() == OBJ_SEQUENCE)
		{
				Sequence* cast = dynamic_cast<Sequence*>(arg2.get());

				for(unsigned int i = 0; i < cast->getLength(); i++)
				{
					std::auto_ptr<Logical> eqOp(static_cast<Logical*>(Equal(arg1->clone(), cast->getObject(i)->clone()).evaluate()));
					if(eqOp->getValue() == true)
						return new Integer(i + 1);
				}

				return new Integer(0);
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_TEXT | OBJ_SEQUENCE, arg2->getType(), 2);
	}

	if(args.size() > 1)
		throw Excep(getLineNumber(), getColumnNumber(), "Invalid number of arguments passed to special function!");

	if(id == SPF_ABS)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());
			if(cast->getValue() < 0)
				return new Integer(-cast->getValue());
			return new Integer(cast->getValue());
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());
			if(cast->getValue() < 0)
				return new Real(-cast->getValue());
			return new Real(cast->getValue());
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	if(id == SPF_SIGN)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());
			if(cast->getValue() < 0)
				return new Integer(-1);
			if(cast->getValue() > 0)
				return new Integer(1);
			return new Integer(0);
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());
			if(cast->getValue() < 0)
				return new Integer(-1);
			if(cast->getValue() > 0)
				return new Integer(1);
			return new Integer(0);
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	if(id == SPF_SQRT)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());

			if(cast->getValue() < 0)
				throw NegativeValueException(getLineNumber(), getColumnNumber(), cast->getValue(), 1);

			double res = sqrt((double) cast->getValue());
			if((long) res == res)
				return new Integer((long) res);
			return new Real(res);
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());

			if(cast->getValue() < 0)
				throw NegativeValueException(getLineNumber(), getColumnNumber(), cast->getValue(), 1);

			double res = sqrt((double) cast->getValue());
			return new Real(res);
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	if(id == SPF_ENTIER)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());
			return new Integer(cast->getValue());
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());
			return new Integer(floor(cast->getValue()));
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	if(id == SPF_ROUND)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());
			return new Integer(cast->getValue());
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());
			long rounded = cast->getValue() < 0.0 ? ceil(cast->getValue() - 0.5) : floor(cast->getValue() + 0.5);
			return new Integer(rounded);
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	if(id == SPF_RAND)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());

			if(cast->getValue() < 0)
				throw NegativeValueException(getLineNumber(), getColumnNumber(), cast->getValue(), 1);

			double f = (double) rand() / RAND_MAX;
			return new Real( f * cast->getValue() );
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());

			if(cast->getValue() < 0)
				throw NegativeValueException(getLineNumber(), getColumnNumber(), cast->getValue(), 1);

			double f = (double) rand() / RAND_MAX;
			return new Real( f * cast->getValue() );
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	if(id == SPF_INTRAND)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());
			if(cast->getValue() < 0)
				throw NegativeValueException(getLineNumber(), getColumnNumber(), cast->getValue(), 1);
			return new Integer( rand() % cast->getValue() + 1 );
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());
			if(cast->getValue() < 0)
				throw NegativeValueException(getLineNumber(), getColumnNumber(), cast->getValue(), 1);
			return new Integer( rand() % (long) cast->getValue() + 1 );
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	if(id == SPF_ISEMPTY)
	{
		return new Logical(arg1->getType() == OBJ_EMPTY);
	}

	if(id == SPF_ISLOG)
	{
		return new Logical(arg1->getType() == OBJ_LOGICAL);
	}

	if(id == SPF_ISINT)
	{
		return new Logical(arg1->getType() == OBJ_INTEGER);
	}

	if(id == SPF_ISREAL)
	{
		return new Logical(arg1->getType() == OBJ_REAL);
	}

	if(id == SPF_ISTEXT)
	{
		return new Logical(arg1->getType() == OBJ_TEXT);
	}

	if(id == SPF_ISSEQ)
	{
		return new Logical(arg1->getType() == OBJ_SEQUENCE);
	}

	if(id == SPF_ISPROC)
	{
		return new Logical(arg1->getType() == OBJ_PROCEDURE);
	}

	if(id == SPF_ISFUN)
	{
		return new Logical(arg1->getType() == OBJ_FUNCTION || arg1->getType() == OBJ_SPFUNCTION);
	}

	if(id == SPF_SIN)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());
			return new Real(sin((double) cast->getValue()));
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());
			return new Real(sin(cast->getValue()));
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	if(id == SPF_COS)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());
			return new Real(cos((double) cast->getValue()));
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());
			return new Real(cos(cast->getValue()));
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	if(id == SPF_TG)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());
			return new Real(tan((double) cast->getValue()));
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());
			return new Real(tan(cast->getValue()));
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	if(id == SPF_ARCSIN)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());
			if(errno == EDOM)
				throw new Excep(getLineNumber(), getColumnNumber(), "Invalid value passed to special function!");
			return new Real(exp((double) cast->getValue()));
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());
			if(errno == EDOM)
				throw new Excep(getLineNumber(), getColumnNumber(), "Invalid value passed to special function!");
			return new Real(exp(cast->getValue()));
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	if(id == SPF_ARCTG)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());
			if(errno == EDOM)
				throw new Excep(getLineNumber(), getColumnNumber(), "Invalid value passed to special function!");
			return new Real(exp((double) cast->getValue()));
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());
			if(errno == EDOM)
				throw new Excep(getLineNumber(), getColumnNumber(), "Invalid value passed to special function!");
			return new Real(exp(cast->getValue()));
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	if(id == SPF_EXP)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());
			return new Real(exp((double) cast->getValue()));
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());
			return new Real(exp(cast->getValue()));
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	if(id == SPF_LN)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());
			return new Real(log((double) cast->getValue()));
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());
			return new Real(log(cast->getValue()));
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	if(id == SPF_LG)
	{
		if(arg1->getType() == OBJ_INTEGER)
		{
			Integer* cast = static_cast<Integer*>(arg1.get());
			return new Real(log10((double) cast->getValue()));
		}

		if(arg1->getType() == OBJ_REAL)
		{
			Real* cast = static_cast<Real*>(arg1.get());
			return new Real(log10(cast->getValue()));
		}

		throw InvalidTypeException(getLineNumber(), getColumnNumber(), OBJ_INTEGER | OBJ_REAL, arg1->getType(), 1);
	}

	throw Excep(getLineNumber(), getColumnNumber(), "Invalid special function!");
}