示例#1
0
文件: token_utils.c 项目: bl0b/tinyap
int node_compare(ast_node_t tok1, ast_node_t tok2) {
	if(tok1==tok2) {
		return 0;
	}
	if(isNil(tok1)) {
		return isNil(tok2)?0:-1;
	} else if(isNil(tok2)) {
		return 1;
	} else if(isAtom(tok1)) {
		return isPair(tok2)
			? 1
			: isAtom(tok2)
				? strcmp(node_compare_tag(Value(tok1)), node_compare_tag(Value(tok2)))
				: 0;
	} else if(isPair(tok1)) {
		if(isPair(tok2)) {
			int ret = node_compare(Car(tok1), Car(tok2));
			return ret?ret:node_compare(Cdr(tok1), Cdr(tok2));
		} else {
			return 1;
		}
	}

	return tok1>tok2?1:-1;
}
示例#2
0
	bool environment::numberArgsOK(boost::any vars, boost::any vals)
	{
		return ((isEMPTY(vars) && isEMPTY(vals)) ||
				isSymbol(vars) ||
				(isPair(vars) && isPair(vals) &&
				 numberArgsOK(rest(vars), rest(vals))));
	}
示例#3
0
static malValuePtr quasiquote(malValuePtr obj)
{
    const malSequence* seq = isPair(obj);
    if (!seq) {
        return mal::list(mal::symbol("quote"), obj);
    }

    if (isSymbol(seq->item(0), "unquote")) {
        // (qq (uq form)) -> form
        checkArgsIs("unquote", 1, seq->count() - 1);
        return seq->item(1);
    }

    const malSequence* innerSeq = isPair(seq->item(0));
    if (innerSeq && isSymbol(innerSeq->item(0), "splice-unquote")) {
        checkArgsIs("splice-unquote", 1, innerSeq->count() - 1);
        // (qq (sq '(a b c))) -> a b c
        return mal::list(
            mal::symbol("concat"),
            innerSeq->item(1),
            quasiquote(seq->rest())
        );
    }
    else {
        // (qq (a b c)) -> (list (qq a) (qq b) (qq c))
        // (qq xs     ) -> (cons (qq (car xs)) (qq (cdr xs)))
        return mal::list(
            mal::symbol("cons"),
            quasiquote(seq->first()),
            quasiquote(seq->rest())
        );
    }
}
示例#4
0
 bool isWellParenthesed(string s, int st, int ed, vector<vector<int> > &f) {
     if (f[st][ed]) {    //searched before
         return f[st][ed] == 1;
     }
     if (st == ed) {
         f[st][ed] = 1;
         return true;
     }
     if ((st > ed) || ((ed-st)%2 == 1)) {
         f[st][ed] = -1;
         return false;
     }
     if (isPair(s[st], s[ed-1]) && isWellParenthesed(s, st+1, ed-1, f)) {
         f[st][ed] = 1;
         return true;
     }
     for (int i = st+2; i < ed-1; i++) {
         if (isWellParenthesed(s, st, i, f) && isWellParenthesed(s, i, ed, f)) {
             f[st][ed] = 1;
             return true;
         }
     }
     f[st][ed] = -1;
     return false;
 }
int isBalanced(char *exp)
{
	int n = 10;
	stack_t s;
	stackInit(&s, n);

	int i;
	for (i = 0; i < n; i++)
	{
		if ((exp[i] == '(') || (exp[i] == '{') || (exp[i] == '['))
		{
			stackPush(&s, exp[i]);
		}
		else if ((exp[i] == ')') || (exp[i] == '}') || (exp[i] == ']'))
		{
			if (stackIsEmpty(&s) || !isPair(s.contents[s.top], exp[i]))
			{
				return -1;
			}
			else
				stackPop(&s);
		}
	}

	return stackIsEmpty(&s) ? 0 : -1;
}
示例#6
0
static const malLambda* isMacroApplication(malValuePtr obj, malEnvPtr env)
{
    if (const malSequence* seq = isPair(obj)) {
        if (malSymbol* sym = DYNAMIC_CAST(malSymbol, seq->first())) {
            if (malEnvPtr symEnv = env->find(sym->value())) {
                malValuePtr value = sym->eval(symEnv);
                if (malLambda* lambda = DYNAMIC_CAST(malLambda, value)) {
                    return lambda->isMacro() ? lambda : NULL;
                }
            }
        }
    }
    return NULL;
}
示例#7
0
int main(){
	int number;

	printf("Ingrese un numero: ");
	if (scanf("%d", &number) != 1){
		printf("Numero invalido\n");
		return 1;
	}
	if (isPair(number) == 1){
		printf("El numero %d es par.\n", number);
	}else{
		printf("El numero %d es impar.\n", number);
	}
	return 0;
}
示例#8
0
double RNAProfileAlignment::bestPairs(size_type node) const
{
  size_type i=node;
  double d1,d2;

  WATCH(DBG_GET_PROFILE_STRUCTURE,"RNAProfileForest::getStructureAlignment",node);

  if(isBase(node))
    return 0;
  else
    {
      // node pairs not
      d1=bestPairs(node+1) + bestPairs(getRightmostBrotherIndex(node+1));

      // node pairs
      d2=label(node).p[ALPHA_PRO_BASEPAIR];

      // left path - righthand best pairs
      i=node+1;
      while(i < size() && isPair(i))
	{
	  d2+=bestPairs(getRightmostBrotherIndex(i+1));
	  i=i+1;
	}

      // right path - lefthand best pairs
      i=getRightmostBrotherIndex(node+1);
      while(isPair(i) && i < size())
	{
	  d2+=bestPairs(i+1);
	  i=getRightmostBrotherIndex(i+1);
	}

      return max(d1,d2);
    }
} 
示例#9
0
 bool isValid(string s) {
     if(s.size() == 0)
         return true;
     stack<char> valid;
     for(int i = 0;i < s.size();i++)
         if(valid.size() == 0)
             valid.push(s[i]);
         else if(isPair(valid.top(),s[i]))
             valid.pop();
         else
             valid.push(s[i]);
     if(valid.size() == 0)
         return true;
     else
         return false;
 }
示例#10
0
int main(void)
{
	int flag;
	node *root;

	while (scanf("%s", str) != EOF) {
		count = 0;
		createBtree(&root);

		flag = isPair(root);

		printf("%d\n", flag);
	}

	return 0;
}
示例#11
0
//***-------------------2014.3.20更新-------------------***
//不需要一个stack,只需要一个记录当前匹配串的最大长度,如果一个右括号进来不且不匹配,当前最大长度就清零
//悲催的是这种思路是不行的,例如"()(()"
int longestValidParentheses2(string s) {
    int max_length = 0;
    int current_length = 0;
    stack<char> dataStack;
    for (int i = 0; i < (int)s.length(); i++) {
        if (dataStack.empty() || !isPair(dataStack.top(), s[i])) {//情况1:stack里没有或者不匹配
            if (s[i] == ')') {//当前这一轮的匹配结束了
                max_length = max(max_length,current_length);
                current_length = 0;
            }
            dataStack.push(s[i]);
        }else{//情况2:匹配
            current_length += 2;
            dataStack.pop();
        }
    }
    return max_length;
}
示例#12
0
 bool isValid(string s) {
     // Start typing your C/C++ solution below
     // DO NOT write int main() function
     
     if (s.length()==0 || s.length()==1) return false;
     
     vector<char> stack;
     for (int i=0;i<s.length();i++) {
         if (isLeft(s[i])) stack.push_back(s[i]);
         else if (isRight(s[i]) && stack.size()>0) {
             if (isPair(stack.back(),s[i])) {
                 stack.pop_back();
             } else return false;
         } else return false;
     }
     
     if (stack.size()==0) return true;
     else return false;
 }
示例#13
0
int longestValidParentheses(string s) {
    int max_length = 0;
    stack<char> dataStack;
    stack<int> numberStack;
    numberStack.push(0);
    for (int i = 0; i < (int)s.length(); i++) {
        if (dataStack.empty() || !isPair(dataStack.top(), s[i])) {//情况1:stack里没有或者不匹配
            dataStack.push(s[i]);
            numberStack.push(i+1);
        }else{//情况2:匹配
            dataStack.pop();
            numberStack.pop();
        }
        if (max_length < i + 1 - numberStack.top()) {
            max_length = i + 1 - numberStack.top();
        }
    }
    return max_length;
}
示例#14
0
////////////////////////////////////////////////////////////////////////////////
// When a Lexer object is constructed with a string, this method walks through
// the stream of low-level tokens.
bool Lexer::token (std::string& token, Lexer::Type& type)
{
  // Eat white space.
  while (isWhitespace (_text[_cursor]))
    utf8_next_char (_text, _cursor);

  // Terminate at EOS.
  if (isEOS ())
    return false;

  // The sequence is specific, and must follow these rules:
  //   - date < duration < uuid < identifier
  //   - dom < uuid
  //   - uuid < hex < number
  //   - url < pair < identifier
  //   - hex < number
  //   - separator < tag < operator
  //   - path < substitution < pattern
  //   - set < number
  //   - word last
  if (isString       (token, type, "'\"") ||
      isDate         (token, type)        ||
      isDuration     (token, type)        ||
      isURL          (token, type)        ||
      isPair         (token, type)        ||
      isUUID         (token, type, true)  ||
      isSet          (token, type)        ||
      isDOM          (token, type)        ||
      isHexNumber    (token, type)        ||
      isNumber       (token, type)        ||
      isSeparator    (token, type)        ||
      isTag          (token, type)        ||
      isPath         (token, type)        ||
      isSubstitution (token, type)        ||
      isPattern      (token, type)        ||
      isOperator     (token, type)        ||
      isIdentifier   (token, type)        ||
      isWord         (token, type))
    return true;

  return false;
}
示例#15
0
文件: ex24a_1knr.c 项目: ambantis/knr
/**
 * @brief Evaluates the char array of parens.
 *
 * The function searches for paren pairs; each pair it finds is removed.
 * The function uses an algorithm of dividing up the the char array into
 * left and right.
 * @param[in,out] p The char array of parens: ()[]{}
 */
bool eval(char p[])
{
    int left = 0;
    int right = 1;
    int len = strLen(p);
    int split = 1;
    while (true) {
        left = dec(p, split);
        right = inc(p, split);
        if (empty(p))
            return true;
        else if (split == len)
            return false;
        else if (isPair(p[left], p[right])) {
            p[left] = p[right] = ' ';
            split++;
        } else
            split++;
    }
    return false;
}
示例#16
0
void RNAProfileAlignment::getSeqAli(string &seq,Uint row, Uint i, Uint j) const
{
	if(i==0 && j==getMaxLength(0))
		seq="";

	if(j==0)
		return;

	// basepair=internal node
	if(isPair(i))
	{
		getSeqAli(seq,row,i+1,noc(i));
		getSeqAli(seq,row,rb(i),j-1);		
	}
	else
	{
		// base=leaf
		seq+=m_lb[i].columnStr[row];
		getSeqAli(seq,row,rb(i),j-1);
	}
}
void cUnitManager::UnitFinished(int unit,UnitInfo *U)
{
//	*l<<" (t="<<U->pBOL->task<<")";
	switch( U->pBOL->task )
	{
	case TASK_CONSTRUCT:
		G->Build->UBuilderFinished(unit,U);
		break;
	case TASK_ASSAULT:
		{
			UAssault.insert(cRAI::iupPair(unit,U));
			UpdateGroupSize();
			Assign(unit,U);
			if( ActiveAttackOrders() )
				SendAttackGroups();
		}
		break;
	case TASK_SCOUT:
		{
			UScout.insert(isPair(unit,sScoutUnitInfo()));
		}
		break;
	case TASK_SUICIDE:
		{
			USuicide.insert(cRAI::iupPair(unit,U));
		}
		break;
	case TASK_SUPPORT:
		{
			USupport.insert(unit);
		}
		break;
	case TASK_TRANSPORT:
		{
			UTrans.insert(itPair(unit,sTransportUnitInfo(U->ud)));
		}
		break;
	}
}
示例#18
0
文件: type.c 项目: jackspirou/orson
bool isJokey(refObject type)
{ bool found;
  struct
  { refFrame  link;
    int       count;
    refObject labeler; } f;

//  JOKING. Traverse OBJECT and set FOUND to TRUE if we visit a joker. We use a
//  layer LABELER to avoid being trapped inside circular structures.

  void joking(refObject term)
  { if (term != nil && isPair(term) && ! gotKey(toss, toss, f.labeler, term))
    { setKey(f.labeler, term, nil, nil);
      switch (toHook(car(term)))
      { case arraysHook:
        case jokerHook:
        case tuplesHook:
        { found = true;
          break; }
        case referHook:
        case rowHook:
        { if (! isForwarded(term))
          { joking(cadr(term)); }
          break; }
        default:
        { while (! found && term != nil)
          { joking(car(term));
            term = cdr(term); }
          break; }}}}

//  Assume TYPE has no jokers, then try to falsify this assumption.

  push(f, 1);
  found = false;
  f.labeler = pushLayer(nil, plainInfo);
  joking(type);
  pop();
  destroyLayer(f.labeler);
  return found; }
示例#19
0
 bool isValid(string s) {
     // Start typing your C/C++ solution below
     // DO NOT write int main() function
     int n = s.size();
     vector<char> stk;
     for (int i=0; i<n; ++i){
         char c = s[i];
         if (isRight(c)){
             if (stk.empty()) return false;
             char stk_c = stk.back();
             if (isPair(stk_c,c)){
                 stk.pop_back();
                 continue;
             }else{
                 return false;
             }
         }else{
             stk.push_back(c);
         }
     }
     if (!stk.empty()) return false;
     else return true;
 }
示例#20
0
文件: Comb.cpp 项目: lazyrun/kenay
Comb::Combs Comb::getComb(const QStringList & cards) const
{
   if (isStraightFlash(cards))
   {
      return Comb::StraightFlash;
   }
   if (isCare(cards))
   {
      return Comb::Care;
   }
   if (isFullHouse(cards))
   {
      return Comb::FullHouse;
   }
   if (isFlash(cards))
   {
      return Comb::Flash;
   }
   if (isStraight(cards))
   {
      return Comb::Straight;
   }
   if (isThreeOfKind(cards))
   {
      return Comb::ThreeOfKind;
   }
   if (isTwoPair(cards))
   {
      return Comb::TwoPair;
   }
   if (isPair(cards))
   {
      return Comb::Pair;
   }

   return Comb::Trash;
}
示例#21
0
文件: serialize.c 项目: bl0b/tinyap
void ast_serialize(const ast_node_t ast,int(*func)(int,void*),void*param) {
	char*srcptr;
	/* if ast is nil, output '()' */
	/*inside_lisp = 1;*/
	if(ast==PRODUCTION_OK_BUT_EMPTY) {
		func('E', param);
		func('M', param);
		func('P', param);
		func('T', param);
		func('Y', param);
		func(0, param);
		return;
	}
	if(!ast) {
		func('(',param);
		func(')',param);
	/* if ast is pair, serialize list */
	} else if(isPair(ast)) {
		func('(',param);
		if(ast->node_flags&IS_FOREST) {
		func('@',param);
		func(' ',param);
		}
		ast_ser_list(ast,func,param);
		func(')',param);
	/* if ast is atom, output atom */
	} else if(isAtom(ast)) {
		srcptr=regstr(getAtom(ast));
		while(*srcptr!=0) {
			escape_chr(&srcptr,func,param, _LISP);
		}
/*		*output+=strlen(getAtom(ast));*/
	}
	func('\0',param);
	/*inside_lisp = 0;*/
}
示例#22
0
void registerBuiltinFunctions(std::unordered_map<Symbol, Value>* variables, Allocator* allocator,
                              SymbolTable* symbol_table)
{

    registerFunction1(variables, allocator, symbol_table, "not",
                      [](Context*, Value obj) { return Value::fromBoolean(!obj.asBoolean()); });

    variables->insert(std::make_pair(
        symbol_table->intern("+"), Value::fromPointer(allocator->make<CFunctionObject>(sum, "+"))));

    variables->insert(
        std::make_pair(symbol_table->intern("*"),
                       Value::fromPointer(allocator->make<CFunctionObject>(prod, "*"))));

    registerFunction2(variables, allocator, symbol_table, "-", [](Context*, Value a, Value b) {
        if (!a.isInteger() || !b.isInteger())
            throw TypeError("-: arguments must be integers");
        return Value::fromInteger(a.asInteger() - b.asInteger());
    });

    registerFunction2(variables, allocator, symbol_table, "/", [](Context*, Value a, Value b) {
        if (!a.isInteger() || !b.isInteger())
            throw TypeError("-: arguments must be integers");
        if (b.asInteger() == 0)
            throw std::runtime_error("/: divide by zero");
        return Value::fromInteger(a.asInteger() / b.asInteger());
    });

    registerFunction2(variables, allocator, symbol_table, "=", [](Context*, Value a, Value b) {
        if (!a.isInteger() || !b.isInteger())
            throw TypeError("=: arguments must be integers");
        return Value::fromBoolean(a.asInteger() == b.asInteger());
    });

    registerFunction2(variables, allocator, symbol_table, "<", [](Context*, Value a, Value b) {
        if (!a.isInteger() || !b.isInteger())
            throw TypeError("<: arguments must be integers");
        return Value::fromBoolean(a.asInteger() < b.asInteger());
    });

    registerFunction2(variables, allocator, symbol_table, ">", [](Context*, Value a, Value b) {
        if (!a.isInteger() || !b.isInteger())
            throw TypeError(">: arguments must be integers");
        return Value::fromBoolean(a.asInteger() > b.asInteger());
    });

    registerFunction2(variables, allocator, symbol_table, "<=", [](Context*, Value a, Value b) {
        if (!a.isInteger() || !b.isInteger())
            throw TypeError("<=: arguments must be integers");
        return Value::fromBoolean(a.asInteger() <= b.asInteger());
    });

    registerFunction2(variables, allocator, symbol_table, ">=", [](Context*, Value a, Value b) {
        if (!a.isInteger() || !b.isInteger())
            throw TypeError(">=: arguments must be integers");
        return Value::fromBoolean(a.asInteger() >= b.asInteger());
    });

    registerFunction2(variables, allocator, symbol_table, "eq?",
                      [](Context*, Value a, Value b) { return Value::fromBoolean(a == b); });

    registerFunction1(variables, allocator, symbol_table, "pair?",
                      [](Context*, Value obj) { return Value::fromBoolean(isPair(obj)); });

    registerFunction2(variables, allocator, symbol_table, "cons",
                      [](Context* ctx, Value a, Value b) {
        return Value::fromPointer(ctx->allocator->make<PairObject>(a, b));
    });

    registerFunction1(variables, allocator, symbol_table, "car", [](Context*, Value pair) {
        if (!isPair(pair))
            throw TypeError("car: 1st argument must be a pair");
        return static_cast<PairObject*>(pair.asPointer())->getCar();
    });

    registerFunction1(variables, allocator, symbol_table, "cdr", [](Context*, Value pair) {
        if (!isPair(pair))
            throw TypeError("cdr: 1st argument must be a pair");
        return static_cast<PairObject*>(pair.asPointer())->getCdr();
    });

    registerFunction1(variables, allocator, symbol_table, "null?",
                      [](Context*, Value obj) { return Value::fromBoolean(obj == Value::Nil); });

    registerFunction1(variables, allocator, symbol_table, "print", [](Context*, Value obj) {
        std::printf("%s\n", obj.toString().c_str());
        return Value::Nil;
    });

    auto callcc_f = allocator->make<CFunctionObject>(callcc, "call-with-current-continuation");
    variables->insert(std::make_pair(symbol_table->intern("call-with-current-continuation"),
                                     Value::fromPointer(callcc_f)));
    variables->insert(
        std::make_pair(symbol_table->intern("call/cc"), Value::fromPointer(callcc_f)));
}
示例#23
0
void RNAProfileAlignment::getStructureAlignmentFromCSF(string &s, deque<double> &pairprob, double t,size_type i, size_type j) const
{
  size_type h;
  double bestPairScore;
  //  list<Uint> leftPairList;
  //list<Uint> rightPairList;
  //Uint bestLeftIndex,bestRightIndex;
  //Uint lastLeftIndex,lastRightIndex;
  
  //  QWATCH(i);
  //  QWATCH(j);	

  if(j==0)
    return;
  
  if(isPair(i))
    {
      // TRACE(DBG_GET_PROFILE_STRUCTURE,"Profile_RNA_Alignment_Forest::getStructureAlignmentFromCSF","basepair");
      // WATCH(DBG_GET_PROFILE_STRUCTURE,"Profile_RNA_Alignment_Forest::getStructureAlignmentFromCSF",m_lb[i].p[ALPHA_BASEPAIR]);

      bestPairScore=bestPairs(i);

      // backtrack best pairs
      if(bestPairScore == bestPairs(i+1) + bestPairs(getRightmostBrotherIndex(i+1)) || m_lb[i].p[ALPHA_PRO_BASEPAIR] < t)
      {
	// i pairs not
	//	cout << "unpaired" << endl;
	getStructureAlignmentFromCSF(s,pairprob,t,i+1,noc(i));
	//	cout << "back to:" << endl;
	//	QWATCH(i);
	//	QWATCH(j);
      }
      else
      {
	//	cout << "paired" << endl;
	// i pairs
	s += '(';
	pairprob.push_back(m_lb[i].p[ALPHA_PRO_BASEPAIR]);
	
	// left path - righthand best pairs
	h=i+1;
	while(h < size() && isPair(h))
	{
	  //	  cout << "left" << endl;
	  //	  QWATCH(h);

	  assert((int)noc(h)-1>=0);
	  getStructureAlignmentFromCSF(s,pairprob,t,rb(h+1),noc(h)-1);
	  h=h+1;
	}


	assert((int)noc(i)-2>=0);
	getStructureAlignmentFromCSF(s,pairprob,t,rb(i+1),noc(i)-2);
	//	cout << "back to:" << endl;
	//	QWATCH(i);
	//	QWATCH(j);

	// right path - lefthand best pairs
	h=getRightmostBrotherIndex(i+1);
	while(h < size() && isPair(h))
	{
	  //	  cout << "right" << endl;
	  //	  QWATCH(h);

	  assert((int)noc(h)-1>=0);
	  getStructureAlignmentFromCSF(s,pairprob,t,h+1,noc(h)-1);
	  //h=h+1;
	  h=getRightmostBrotherIndex(h+1);
	}      
 

	s += ')';
	pairprob.push_back(m_lb[i].p[ALPHA_PRO_BASEPAIR]);
      }
    }
  else
    {
      s+= '.';
      pairprob.push_back(m_lb[i].p[ALPHA_PRO_BASE]);
    }
  
  // right forest
  getStructureAlignmentFromCSF(s,pairprob,t,rb(i),j-1);
}
示例#24
0
文件: Cell.cpp 项目: wibbe/scheme-cpp
 Cell Cell::cdr() const
 {
   if (!isPair())
     return Cell();
   return Cell(m_scheme, pair_cdr(m_value));
 }
示例#25
0
bool Hand::isFullHouse() const
{
    return (isPair() && isThreeOfAKind());
}
示例#26
0
文件: type.c 项目: jackspirou/orson
refObject skolemize(refObject layer, refObject type)
{ struct
  { refFrame  link;
    int       count;
    refObject first;
    refObject labeler;
    refObject last;
    refObject layer;
    refObject next;
    refObject type; } f0;

//  IS SKOLEMIZABLE. Test if TYPE, which is ground in LAYER, can be the base of
//  a Skolem type. It can be, if it has a subtype that's different from itself.
//  For example, OBJ has an infinite number of such subtypes but INT0 has none.
//  The WHILE loop helps simulate tail recursions.

  bool isSkolemizable(refObject layer, refObject type)
  { while (true)
    { if (isName(type))
      { getKey(r(layer), r(type), layer, type); }
      else

//  Visit a type. If LABELER says we've been here before, then return false. If
//  we haven't, then record TYPE in LABELER so we won't come here again.

      if (isPair(type))
      { if (gotKey(toss, toss, f0.labeler, type))
        { return false; }
        else
        { refObject pars;
          setKey(f0.labeler, type, nil, nil);
          switch (toHook(car(type)))

//  Visit a trivially Skolemizable type. An ALTS, FORM, or GEN type can have an
//  ALTS type as a subtype. A REF or ROW type can have NULL as a subtype.

          { case altsHook:
            case arraysHook:
            case formHook:
            case genHook:
            case jokerHook:
            case referHook:
            case rowHook:
            case skoHook:
            case tuplesHook:
            { return true; }

//  Visit a type that is trivially not Skolemizable.

            case cellHook:
            case char0Hook:
            case char1Hook:
            case int0Hook:
            case int1Hook:
            case int2Hook:
            case listHook:
            case nullHook:
            case real0Hook:
            case real1Hook:
            case strTypeHook:
            case symHook:
            case voidHook:
            { return false; }

//  Visit an ARRAY type. It's Skolemizable if its base type is.

            case arrayHook:
            { type = caddr(type);
              break; }

//  Visit a PROC type. It's Skolemizable if (1) it has a Skolemizable parameter
//  type, (2) it has the missing name NO NAME as a parameter name, (3) it has a
//  Skolemizable yield type.

            case procHook:
            { type = cdr(type);
              pars = car(type);
              while (pars != nil)
              { pars = cdr(pars);
                if (car(pars) == noName)
                { return true; }
                else
                { pars = cdr(pars); }}
              pars = car(type);
              while (pars != nil)
              { if (isSkolemizable(layer, car(pars)))
                { return true; }
                else
                { pars = cddr(pars); }}
              type = cadr(type);
              break; }

//  Visit a TUPLE type. It's Skolemizable if it has a Skolemizable slot type or
//  if it has the missing name NO NAME as a slot name.

            case tupleHook:
            { pars = cdr(type);
              while (pars != nil)
              { pars = cdr(pars);
                if (car(pars) == noName)
                { return true; }
                else
                { pars = cdr(pars); }}
              pars = cdr(type);
              while (pars != nil)
              { if (isSkolemizable(layer, car(pars)))
                { return true; }
                else
                { pars = cddr(pars); }}
              return false; }

//  Visit a prefix type. It's Skolemizable if its base type is.

            case typeHook:
            case varHook:
            { type = cadr(type);
              break; }

//  Visit an illegal type. We should never get here.

            default:
            { fail("Got ?%s(...) in isSkolemizable!", hookTo(car(type))); }}}}

//  Visit an illegal object. We should never get here either.

      else
      { fail("Got bad type in isSkolemizable!"); }}}

//  Lost? This is SKOLEMIZE's body. These identities show what's going on.
//
//    S(type T B)  =>  T S(B)
//    S(U)         =>  ?sko(U)
//    S(V)         =>  V
//
//  Here S(X) is the Skolem type for type X. T is a series of zero or more TYPE
//  prefixes. B is a type, U is a type with at least one subtype different from
//  itself, and V is a type with no subtypes different from itself.

  push(f0, 6);
  f0.labeler = pushLayer(nil, plainInfo);
  f0.layer = layer;
  f0.type = type;
  while (isName(f0.type))
  { getKey(r(f0.layer), r(f0.type), f0.layer, f0.type); }
  if (isCar(f0.type, typeHook))
  { f0.type = cadr(f0.type);
    if (isSkolemizable(f0.layer, f0.type))
    { if (isCar(f0.type, typeHook))
      { f0.first = f0.last = makePair(hooks[typeHook], nil);
        f0.type = cadr(f0.type);
        while (isCar(f0.type, typeHook))
        { f0.next = makePair(hooks[typeHook], nil);
          cdr(f0.last) = makePair(f0.next, nil);
          f0.last = f0.next;
          f0.type = cadr(f0.type); }
        f0.next = makePrefix(skoHook, f0.type);
        cdr(f0.last) = makePair(f0.next, nil); }
      else
      { f0.first = makePrefix(skoHook, f0.type); }}
    else
    { f0.first = makePair(car(f0.type), cdr(f0.type)); }}
  else
  { fail("Type type expected in skolemize!"); }
  pop();
  destroyLayer(f0.labeler);
  return f0.first; }
示例#27
0
int main(int argv, char **argc) {
	robot_if_t ri;
	int major, minor, x_dist_diff, square_count, prev_square_area_1 = 0, prev_square_area_2 = 0;
	IplImage *image = NULL, *hsv = NULL, *threshold_1 = NULL, *threshold_2 = NULL, *final_threshold = NULL;
	squares_t *squares, *biggest_1, *biggest_2, , *pair_square_1, *pair_square_2, *sq_idx;
	bool same_square;
	bool hasPair = 0;
	
	square_count = 0;
	
	// Make sure we have a valid command line argument
	if(argv <= 1) {
		printf("Usage: robot_test <address of robot>\n");	
		exit(-1);
	}

	ri_api_version(&major, &minor);
	printf("Robot API Test: API Version v%i.%i\n", major, minor);

	// Setup the robot with the address passed in
	if(ri_setup(&ri, argc[1], 0)) {
		printf("Failed to setup the robot!\n");
		exit(-1);
	}

	// Setup the camera
	if(ri_cfg_camera(&ri, RI_CAMERA_DEFAULT_BRIGHTNESS, RI_CAMERA_DEFAULT_CONTRAST, 5, RI_CAMERA_RES_640, RI_CAMERA_QUALITY_LOW)) {
		printf("Failed to configure the camera!\n");
		exit(-1);
	}

	// Create a window to display the output
	//cvNamedWindow("Rovio Camera", CV_WINDOW_AUTOSIZE);
	cvNamedWindow("Biggest Square", CV_WINDOW_AUTOSIZE);
	cvNamedWindow("Thresholded", CV_WINDOW_AUTOSIZE);

	// Create an image to store the image from the camera
	image = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3);

	// Create an image to store the HSV version in
	// We configured the camera for 640x480 above, so use that size here
	hsv = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3);

	// And an image for each thresholded version
	threshold_1 = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 1);
	threshold_2 = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 1);
	final_threshold = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 1);

	// Move the head up to the middle position
	ri_move(&ri, RI_HEAD_MIDDLE, RI_FASTEST);
	
	// Action loop
	do {
		// Update the robot's sensor information
		if(ri_update(&ri) != RI_RESP_SUCCESS) {
			printf("Failed to update sensor information!\n");
			continue;
		}

		// Get the current camera image and display it
		if(ri_get_image(&ri, image) != RI_RESP_SUCCESS) {
			printf("Unable to capture an image!\n");
			continue;
		}
		//cvShowImage("Rovio Camera", image);

		// Convert the image from RGB to HSV
		cvCvtColor(image, hsv, CV_BGR2HSV);

		// Pick out the first range of pink color from the image
		cvInRangeS(hsv, RC_PINK_LOW_1, RC_PINK_HIGH_1, threshold_1);
		
		// Pick out the second range of pink color from the image
		cvInRangeS(hsv, RC_PINK_LOW_2, RC_PINK_HIGH_2, threshold_2);
		
		// compute the final threshold image by using cvOr
		cvOr(threshold_1, threshold_2, final_threshold, NULL);
		

		cvShowImage("Thresholded", final_threshold);
		
		// Find the squares in the image
		squares = ri_find_squares(final_threshold, RI_DEFAULT_SQUARE_SIZE);
		
		if( squares != NULL ) {
			printf("Sorting squares!\n");
			sort_squares(squares);
			printf("Sort Complete!\n");
			printAreas(squares);
			printf("Done printing");
		
			//find biggest pair (if it exists)
			sq_idx = squares;
			
			while(sq_idx != NULL){
				if(sq_idx->next == NULL) break;
				else if(isPair(sq_idx, sq_idx->next, 0.75)){
					hasPair = 1;
					break;
				}
				sq_idx = sq_idx->next;
			}
		
			printf("Pair ID complete!\n");
			
			if(hasPair){
				printf("Pair found.\n");
				//draw_green_X(sq_idx, image);
				//draw_green_X(sq_idx->next, image);
				biggest_1 = sq_idx;
				biggest_2 = sq_idx->next;
				
				
				
			}
			else {
				printf("Pair not found.  Marking largest.\n");
				draw_red_X(squares, image);
				
				//temporary:
				biggest_1 = squares;
				biggest_2 = squares;
			}
			hasPair = 0;
		}
		else {
			printf("No squares found.\n");
		}
		
		hasPair = 0;
		
		if(biggest_1 != NULL){
			draw_green_X(biggest_1, image);
			printf("Area 1 = %d", biggest_1->area);
		}
		
		//we only see the last pair of squares, go straight ahead until IR_Detect stops the robot
		if (square_count == 3){	
			ri_move(&ri, RI_MOVE_FORWARD, 1);
			if (ri_IR_Detected(&ri)) {
				square_count++;
				printf("Object detected, square_count = %d\n", square_count);
			}		
	
		}
		//once the robot is at the intersection, rotate right until it detects a pair of squares
		else if(square_count == 4){
			printf("Rotating\n");
			
			if (biggest_1 != NULL && biggest_2 != NULL && (biggest_1->area - biggest_2->area) < 500){
				square_count++;
				printf("New Path Found\n");
			}
			ri_move(&ri, RI_TURN_RIGHT, 7); 
			
		}
		else{
			/*
			 * 	If we only find a single usable largest square:
			 * 		if square is on left of screen, turn right, strafe right
			 * 		if square is on right of screen, turn left, strafe left
			 */	
			
			
			
			if(biggest_1 != NULL && biggest_2 != NULL ) {
				draw_red_X(biggest_2, image);
				printf("\tArea 2 = %d\n", biggest_2->area);
				
				//get the difference in distance between the two biggest squares and the center vertical line
				x_dist_diff = get_square_diffence(biggest_1, biggest_2, image);
				get_diff_in_y(biggest_1, biggest_2);
				
				//when the camera can't detect a pair of squares, which means now the second biggest square
				//is much smaller than the first biggest square
				if ((biggest_1->area - biggest_2->area) > 500){
					//if both squares are at the left side of the center line
					if (biggest_1->center.x < image->width/2 && biggest_2->center.x < image->width/2){
						printf("rotate right at speed = 6\n");
						ri_move(&ri, RI_TURN_RIGHT, 6); 
					}
					//if both squares are at the right side of the center line
					else if (biggest_1->center.x > image->width/2 && biggest_2->center.x > image->width/2){
						printf("rotate left at speed = 6\n");
						ri_move(&ri, RI_TURN_LEFT, 6); 
					}
					//if the center line is in the middle of the two biggest squares
					else if (biggest_1->center.x < image->width/2 && biggest_2->center.x > image->width/2 ){
						printf("rotate right at speed = 2\n");
						ri_move(&ri, RI_TURN_RIGHT, 2); 
						
					}
					else{
						printf("rotate left at speed = 2\n");
						ri_move(&ri, RI_TURN_LEFT, 2); 
					}
					
				}
				else{
					//increment square_count whenever the robot pass by a pair of squares
					if (prev_square_area_1 != 0 && prev_square_area_2 != 0 && 
						biggest_1->area < prev_square_area_1  && biggest_2->area < prev_square_area_2 ){
						square_count++;
						printf("square count = %d\n", square_count);
					}
					//rotate to the left
					if (x_dist_diff < -40){
						printf("rotate left at speed = 6\n");
						ri_move(&ri, RI_TURN_LEFT, 6); 
					}
					//rotate to the right
					else if (x_dist_diff > 40){
						printf("rotate right at speed = 6\n");
						ri_move(&ri, RI_TURN_RIGHT, 6);
					}
					prev_square_area_1 = biggest_1->area;
					prev_square_area_2 = biggest_2->area;
					
				}
				ri_move(&ri, RI_MOVE_FORWARD, 5);
			}
			//once the camera can't detect any squares, make the robot go backwards
			else if (biggest_1 == NULL && biggest_2 == NULL){
				printf("Move Backwards\n");
				ri_move(&ri, RI_MOVE_BACKWARD , 1); 
			}
		}

		// display a straight vertical line
		draw_vertical_line(image);
		
		// Display the image with the drawing oon ito
		cvShowImage("Biggest Square", image);
		
		// Update the UI (10ms wait)
		cvWaitKey(10);
	
		// Release the square data
		while(squares != NULL) {
			
			sq_idx = squares->next;
			free(squares);
			squares = sq_idx;	
		}
		biggest_1 = NULL;
		biggest_2 = NULL;

		// Move forward unless there's something in front of the robot
		/*if(!ri_IR_Detected(&ri))
			ri_move(&ri, RI_MOVE_FORWARD, RI_SLOWEST);*/
		//printf("Loop Complete\n");
		//getc(stdin);
	} while(1);

	// Clean up (although we'll never get here...)
	//cvDestroyWindow("Rovio Camera");
	cvDestroyWindow("Biggest Square");
	cvDestroyWindow("Thresholded");
	
	// Free the images
	cvReleaseImage(&threshold_1);
	cvReleaseImage(&threshold_2);
	cvReleaseImage(&final_threshold);
	cvReleaseImage(&hsv);
	cvReleaseImage(&image);

	return 0;
}
示例#28
0
void emitStatement(refObject term, set wraps)

//  PRE EMIT. Write an open brace if needed.

{ void preEmit(int hook)
  { if (isInSet(hook, wraps))
    { writeChar(target, '{'); }}

//  POST EMIT. Write a close brace if needed.

  void postEmit(int hook)
  { if (isInSet(hook, wraps))
    { writeChar(target, '}'); }}

//  Dispatch to an appropriate case based on TERM's outer hook.

   if (isPair(term))
   { switch (toHook(car(term)))

//  Write C code for a CASE clause.

    { case caseHook:
      { refObject subterm;
        preEmit(caseHook);
        term = cdr(term);
        writeFormat(target, "switch");
        writeChar(target, '(');
        emitExpression(car(term), 13);
        writeChar(target, ')');
        writeChar(target, '{');
        term = cdr(term);
        while (cdr(term) != nil)
        { emitLabels(car(term));
          term = cdr(term);
          subterm = car(term);
          if (isEffected(subterm))
          { emitStatement(subterm, withSet); }
          writeFormat(target, "break");
          writeChar(target, ';');
          term = cdr(term); }
        subterm = car(term);
        if (isEffected(subterm))
        { writeFormat(target, "default");
          writeChar(target, ':');
          emitStatement(subterm, withSet); }
        writeChar(target, '}');
        postEmit(caseHook);
        break; }

//  Write C code for an IF clause.

      case ifHook:
      { refObject subterm;
        preEmit(ifHook);
        term = cdr(term);
        while (true)
        { writeFormat(target, "if");
          writeChar(target, '(');
          emitExpression(car(term), 13);
          writeChar(target, ')');
          term = cdr(term);
          subterm = car(term);
          if (isEffected(subterm))
          { emitStatement(subterm, ifLastWithSet); }
          else
          { writeChar(target, ';'); }
          term = cdr(term);
          if (cdr(term) == nil)
          { subterm = car(term);
            if (isEffected(subterm))
            { writeFormat(target, "else");
              writeBlank(target);
              if (isCar(subterm, ifHook))
              { term = cdr(subterm); }
              else
              { emitStatement(subterm, lastWithSet);
                break; }}
            else
            { break; }}
          else
          { writeFormat(target, "else");
            writeBlank(target); }}
        postEmit(ifHook);
        break; }

//  Write C code for a LAST clause.

      case lastHook:
      { refObject subterm;
        preEmit(lastHook);
        term = cdr(term);
        while (term != nil)
        { subterm = car(term);
          if (isEffected(subterm))
          { emitStatement(subterm, withSet); }
          term = cdr(term); }
        postEmit(lastHook);
        break; }

//  Write C code for a WHILE clause.

      case whileHook:
      { preEmit(whileHook);
        term = cdr(term);
        writeFormat(target, "while");
        writeChar(target, '(');
        emitExpression(car(term), 13);
        writeChar(target, ')');
        term = cadr(term);
        if (isEffected(term))
        { emitStatement(term, lastWithSet); }
        else
        { writeChar(target, ';'); }
        postEmit(whileHook);
        break; }

//  Write C code for a WITH clause.

      case withHook:
      { refObject frame;
        preEmit(withHook);
        term = cdr(term);
        frame = car(term);
        term = cdr(term);
        if (frame == nil)
        { emitVariableDeclarations(term);
          emitFunctionDefinitions(true, term);
          emitVariableDefinitions(nil, term);
          term = car(lastPair(term));
          if (isEffected(term))
          { emitStatement(term, withSet); }}
        else
        { emitFrameDeclaration(frame, term);
          emitVariableDeclarations(term);
          emitFunctionDefinitions(true, term);
          emitFramePush(frame, frameLength(term));
          emitFrameInitialization(frame, term);
          emitVariableDefinitions(frame, term);
          term = car(lastPair(term));
          if (isEffected(term))
          { emitStatement(term, withSet); }
          emitFramePop(frame); }
        postEmit(withHook);
        break; }

//  Other TERMs become C expressions.

      default:
      { if (isEffected(term))
        { emitExpression(term, 13);
          writeChar(target, ';'); }
        break; }}}
  else
  { if (isEffected(term))
    { emitExpression(term, 13);
      writeChar(target, ';'); }}}
示例#29
0
文件: syntax.c 项目: jarvinet/scheme
void isApplication(Register result, Register exp)
{
    makeBoolean(result, isPair(exp));
}