Search Results

Search found 5101 results on 205 pages for 'expression trees'.

Page 11/205 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • How do I optimize this postfix expression tree for speed?

    - by Peter Stewart
    Thanks to the help I received in this post: I have a nice, concise recursive function to traverse a tree in postfix order: deque <char*> d; void Node::postfix() { if (left != __nullptr) { left->postfix(); } if (right != __nullptr) { right->postfix(); } d.push_front(cargo); return; }; This is an expression tree. The branch nodes are operators randomly selected from an array, and the leaf nodes are values or the variable 'x', also randomly selected from an array. char *values[10]={"1.0","2.0","3.0","4.0","5.0","6.0","7.0","8.0","9.0","x"}; char *ops[4]={"+","-","*","/"}; As this will be called billions of times during a run of the genetic algorithm of which it is a part, I'd like to optimize it for speed. I have a number of questions on this topic which I will ask in separate postings. The first is: how can I get access to each 'cargo' as it is found. That is: instead of pushing 'cargo' onto a deque, and then processing the deque to get the value, I'd like to start processing it right away. I don't yet know about parallel processing in c++, but this would ideally be done concurrently on two different processors. In python, I'd make the function a generator and access succeeding 'cargo's using .next(). But I'm using c++ to speed up the python implementation. I'm thinking that this kind of tree has been around for a long time, and somebody has probably optimized it already. Any Ideas? Thanks

    Read the article

  • Access Expression problem: it's too complex, so how do I turn it in to a function?

    - by Mike
    Access 2007 is telling me that my new expression is to complex. It used to work when we had 10 service levels, but now we have 19! Great! I've asked this question in SuperUser and someone suggested I try it over here. Suggestions are I turn it in to a function - but I'm not sure where to begin and what the function would look like. My expression is checking the COST of our services in the [PriceCharged] field and then assigning the appropriate HOURS [Servicelevel] when I perform a calculation to work out how much REVENUE each colleague has made when working for a client. The [EstimatedTime] field stores the actual hours each colleague has worked. [EstimatedTime]/[ServiceLevel]*[PriceCharged] Below is the breakdown of my COST to HOURS expression. I've put them on different lines to make it easier to read - please do not be put off by the length of this post, it's all the same info in the end. Many thanks,Mike ServiceLevel: IIf([pricecharged]=100(COST),6(HOURS), IIf([pricecharged]=200 Or [pricecharged]=210,12.5, IIf([pricecharged]=300,19, IIf([pricecharged]=400 Or [pricecharged]=410,25, IIf([pricecharged]=500,31, IIf([pricecharged]=600,37.5, IIf([pricecharged]=700,43, IIf([pricecharged]=800 Or [pricecharged]=810,50, IIf([pricecharged]=900,56, IIf([pricecharged]=1000,62.5, IIf([pricecharged]=1100,69, IIf([pricecharged]=1200 Or [pricecharged]=1210,75, IIf([pricecharged]=1300 Or [pricecharged]=1310,100, IIf([pricecharged]=1400,125, IIf([pricecharged]=1500,150, IIf([pricecharged]=1600,175, IIf([pricecharged]=1700,200, IIf([pricecharged]=1800,225, IIf([pricecharged]=1900,250,0)))))))))))))))))))

    Read the article

  • Should I be using Expression Blend to design really dynamic UIs?

    - by Robert Rossney
    My company's product is, at its core, a framework for developing metadata-driven UIs. I don't know how to characterize it less succinctly than that, and hope I won't need to for purposes of this question, but we'll see. I've been trying to come up to speed on WPF, and have been building UI prototypes here and there, and recently I decided to see if I could use Expression Blend to help with the design of these UIs. And I'm pretty mystified at this point. It appears to me as though Expresssion Blend is designed with the expectation that you already know all of the objects that are going to be present in the UI at design time. But our program generates these object dynamically at runtime. For instance, a data row might be presented in a horizontal StackPanel containing alternating TextBlocks (for captions) and TextBoxes (for data fields). The number of these objects depends on metadata about the number of columns in the data row. I can, pretty readily, write code that runs through a metadata record and populates a StackPanel dynamically, setting up the binding of all of the controls to properties in either the data or metadata. (A TextBox's Width might be bound to metadata, while its Text is bound to data.) But I can't even begin to figure out how to do something like this in Expression Blend. I can manually create all these controls, so that I have a set of controls that I can apply styles to and work out the visual design of the app, but it's really a pain to do this. I can write code that goes through my data model and emits XAML for all these controls, I suppose, and then copy and paste it. But I'm going to feel really stupid if it turns out there a way to do this sort of thing in Expression Blend and I've dropped back and punted because I'm too dim to figure out the right way to think of it. Is this enough information for someone to try formulating an answer?

    Read the article

  • Regular expression help

    - by DJPB
    I there I'm working on a C# app, and I get a string with a date or part of a date and i need to take day, month and year for that string ex: string example='31-12-2010' string day = Regex.Match(example, "REGULAR EXPRESSION FOR DAY").ToString(); string month = Regex.Match(example, "REGULAR EXPRESSION FOR MONTH").ToString() string year = Regex.Match(example, "REGULAR EXPRESSION FOR YEAR").ToString() day = "31" month = "12" year = "2010" ex2: string example='12-2010' string month = Regex.Match(example, "REGULAR EXPRESSION FOR MONTH").ToString() string year = Regex.Match(example, "REGULAR EXPRESSION FOR YEAR").ToString() month = "12" year = "2010" any idea? tks

    Read the article

  • Translate a<b to IR Trees

    - by drozzy
    I have to translate the mini-java (java like language) statements into intermediate-representation trees. But for this question I have no idea what it is asking... a>b moves a 1 or 0 into some newly defined temporary, and whose right-hand side is a temporary Does the wording make sense to anyone? (I am using the Java compilers book, and it is question 7.2d) in ch7.)

    Read the article

  • javascript compare two DOM trees

    - by Paul
    I want to compare the change of a DOM node after a user event is fired on it; but I don't know on which element a user would fire, so my idea is to (1) save the DOM tree before an event and (2) compare the saved tree with the updated DOM tree when an event is fired. My question are (1) is there any better way? and (2) if there is no other way, what would be the fast algorithm to compare two DOM trees?

    Read the article

  • Languages for implementing decision trees

    - by Shailesh Tainwala
    What would be a good choice of programming language in which to implement a decision tree? The results of the implementation will be for personal use only, so no need to consider ability to publish etc. I have heard that Octave is a good option, can anyone explain why a matrix based language is recommended for implementing decision trees?

    Read the article

  • Linq Expression Trees in Compact Framework.

    - by Michal Drozdowicz
    The lack of expression trees in Compact Framework has bugged me for some time now, but I haven't really looked for a solution. Today, I've found a blog post about an alternative System.Linq.Expressions built on top of Mono System.Core and used e.g. by db4o (you can find it here). My question is - have you used this library and if so, what were your experiences with it (especially regarding performance)?

    Read the article

  • Generate regular expression to match strings from the list A, but not from list B

    - by Vlad
    I have two lists of strings ListA and ListB. I need to generate a regular expression that will match all strings in ListA and will not match any string in ListB. The strings could contain any combination of characters, numbers and punctuation. If a string appears on ListA it is guaranteed that it will not be in the ListB. If a string is not in either of these two lists I don't care what the result of the matching should be. The lists typically contain thousands of strings, and strings are fairly similar to each other. I know the trivial answer to this question, which is just generate a regular expression of the form (Str1)|(Str2)|(Str3) where StrN is the string from ListA. But I am looking for a more efficient way to do this. Ideal solution would be some sort of tool that will take two lists and generate a Java regular expression for this. Update 1: By "efficient", I mean to generate expression that is shorter than trivial solution. The ideal algorithm would generate the shorted possible expression. Here are some examples. ListA = { C10 , C15, C195 } ListB = { Bob, Billy } The ideal expression would be /^C1.+$/ Another example, note the third element of ListB ListA = { C10 , C15, C195 } ListB = { Bob, Billy, C25 } The ideal expression is /^C[^2]{1}.+$/ The last example ListA = { A , D ,E , F , H } ListB = { B , C , G , I } The ideal expression is the same as trivial solution which is /^(A|D|E|F|H)$/ Also, I am not looking for the ideal solution, anything better than trivial would help. I was thinking along the lines of generating the list of trivial solutions, and then try to merge the common substrings while watching that we don't wander into ListB territory. *Update 2: I am not particularly worried about the time it takes to generate the RegEx, anything under 10 minutes on the modern machine is acceptable

    Read the article

  • k-d tree implementation [closed]

    - by user466441
    when i run my code and debugged,i got this error - this 0x00093584 {_Myproxy=0x00000000 _Mynextiter=0x00000000 } std::_Iterator_base12 * const - _Myproxy 0x00000000 {_Mycont=??? _Myfirstiter=??? } std::_Container_proxy * _Mycont CXX0017: Error: symbol "" not found _Myfirstiter CXX0030: Error: expression cannot be evaluated + _Mynextiter 0x00000000 {_Myproxy=??? _Mynextiter=??? } std::_Iterator_base12 * but i dont know what does it means,code is this #include<iostream> #include<vector> #include<algorithm> using namespace std; struct point { float x,y; }; vector<point>pointleft(4); vector<point>pointright(4); //we are going to implement two comparison function for x and y coordinates,we need it in calculation of median (we should sort vector //by x or y according to depth informaton,is depth even or odd. bool sortby_X(point &a,point &b) { return a.x<b.x; } bool sortby_Y(point &a,point &b) { return a.y<b.y; } //so i am going to implement to median finding algorithm,one for finding median by x and another find median by y point medianx(vector<point>points) { point temp; sort(points.begin(),points.end(),sortby_X); temp=points[(points.size()/2)]; return temp; } point mediany(vector<point>points) { point temp; sort(points.begin(),points.end(),sortby_Y); temp=points[(points.size()/2)]; return temp; } //now construct basic tree structure struct Tree { float x,y; Tree(point a) { x=a.x; y=a.y; } Tree *left; Tree *right; }; Tree * build_kd( Tree *root,vector<point>points,int depth) { point temp; if(points.size()==1)// that point is as a leaf { if(root==NULL) root=new Tree(points[0]); return root; } if(depth%2==0) { temp=medianx(points); root=new Tree(temp); for(int i=0;i<points.size();i++) { if (points[i].x<temp.x) pointleft[i]=points[i]; else pointright[i]=points[i]; } } else { temp=mediany(points); root=new Tree(temp); for(int i=0;i<points.size();i++) { if(points[i].y<temp.y) pointleft[i]=points[i]; else pointright[i]=points[i]; } } return build_kd(root->left,pointleft,depth+1); return build_kd(root->right,pointright,depth+1); } void print(Tree *root) { while(root!=NULL) { cout<<root->x<<" " <<root->y; print(root->left); print(root->right); } } int main() { int depth=0; Tree *root=NULL; vector<point>points(4); float x,y; int n=4; for(int i=0;i<n;i++) { cin>>x>>y; points[i].x=x; points[i].y=y; } root=build_kd(root,points,depth); print(root); return 0; } i am trying ti implement in c++ this pseudo code tuple function build_kd_tree(int depth, set points): if points contains only one point: return that point as a leaf. if depth is even: Calculate the median x-value. Create a set of points (pointsLeft) that have x-values less than the median. Create a set of points (pointsRight) that have x-values greater than or equal to the median. else: Calculate the median y-value. Create a set of points (pointsLeft) that have y-values less than the median. Create a set of points (pointsRight) that have y-values greater than or equal to the median. treeLeft = build_kd_tree(depth + 1, pointsLeft) treeRight = build_kd_tree(depth + 1, pointsRight) return(median, treeLeft, treeRight) please help me what this error means?

    Read the article

  • VB.NET IF() Coalesce and “Expression Expected” Error

    - by Jeff Widmer
    I am trying to use the equivalent of the C# “??” operator in some VB.NET code that I am working in. This StackOverflow article for “Is there a VB.NET equivalent for C#'s ?? operator?” explains the VB.NET IF() statement syntax which is exactly what I am looking for... and I thought I was going to be done pretty quickly and could move on. But after implementing the IF() statement in my code I started to receive this error: Compiler Error Message: BC30201: Expression expected. And no matter how I tried using the “IF()” statement, whenever I tried to visit the aspx page that I was working on I received the same error. This other StackOverflow article Using VB.NET If vs. IIf in binding/rendering expression indicated that the VB.NET IF() operator was not available until VS2008 or .NET Framework 3.5.  So I checked the Web Application project properties but it was targeting the .NET Framework 3.5: So I was still not understanding what was going on, but then I noticed the version information in the detailed compiler output of the error page: This happened to be a C# project, but with an ASPX page with inline VB.NET code (yes, it is strange to have that but that is the project I am working on).  So even though the project file was targeting the .NET Framework 3.5, the ASPX page was being compiled using the .NET Framework 2.0.  But why?  Where does this get set?  How does ASP.NET know which version of the compiler to use for the inline code? For this I turned to the web.config.  Here is the system.codedom/compilers section that was in the web.config for this project: <system.codedom>     <compilers>         <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">             <providerOption name="CompilerVersion" value="v3.5" />             <providerOption name="WarnAsError" value="false" />         </compiler>     </compilers> </system.codedom> Keep in mind that this is a C# web application project file but my aspx file has inline VB.NET code.  The web.config does not have any information for how to compile for VB.NET so it defaults to .NET 2.0 (instead of 3.5 which is what I need). So the web.config needed to include the VB.NET compiler option.  Here it is with both the C# and VB.NET options (I copied the VB.NET config from a new VB.NET Web Application project file).     <system.codedom>         <compilers>             <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">                 <providerOption name="CompilerVersion" value="v3.5" />                 <providerOption name="WarnAsError" value="false" />             </compiler>       <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">         <providerOption name="CompilerVersion" value="v3.5"/>         <providerOption name="OptionInfer" value="true"/>         <providerOption name="WarnAsError" value="false"/>       </compiler>     </compilers>     </system.codedom>   So the inline VB.NET code on my aspx page was being compiled using the .NET Framework 2.0 when it really needed to be compiled with the .NET Framework 3.5 compiler in order to take advantage of the VB.NET IF() coalesce statement.  Without the VB.NET web.config compiler option, the default is to compile using the .NET Framework 2.0 and the VB.NET IF() coalesce statement does not exist (at least in the form that I want it in).  FYI, there is an older IF statement in VB.NET 2.0 compiler which is why it is giving me the unusual “Expression Expected” error message – see this article for when VB.NET got the new updated version. EDIT (2011-06-20): I had made a wrong assumption in the first version of this blog post.  After a little more research and investigation I was able to figure out that the issue was in the web.config and not with the IIS App Pool.  Thanks to the comment from James which forced me to look into this again.

    Read the article

  • Helper method to Replace/Remove characters that do not match the Regular Expression

    - by Michael Freidgeim
    I have a few fields, that use regEx for validation. In case if provided field has unaccepted characters, I don't want to reject the whole field, as most of validators do, but just remove invalid characters. I am expecting to keep only Character Classes for allowed characters and created a helper method to strip unaccepted characters. The allowed pattern should be in Regex format, expect them wrapped in square brackets. function will insert a tilde after opening squere bracket , according to http://stackoverflow.com/questions/4460290/replace-chars-if-not-match.  [^ ] at the start of a character class negates it - it matches characters not in the class.I anticipate that it could work not for all RegEx describing valid characters sets,but it works for relatively simple sets, that we are using.         /// <summary>               /// Replaces  not expected characters.               /// </summary>               /// <param name="text"> The text.</param>               /// <param name="allowedPattern"> The allowed pattern in Regex format, expect them wrapped in brackets</param>               /// <param name="replacement"> The replacement.</param>               /// <returns></returns>               /// //        http://stackoverflow.com/questions/4460290/replace-chars-if-not-match.               //http://stackoverflow.com/questions/6154426/replace-remove-characters-that-do-not-match-the-regular-expression-net               //[^ ] at the start of a character class negates it - it matches characters not in the class.               //Replace/Remove characters that do not match the Regular Expression               static public string ReplaceNotExpectedCharacters( this string text, string allowedPattern,string replacement )              {                     allowedPattern = allowedPattern.StripBrackets( "[", "]" );                      //[^ ] at the start of a character class negates it - it matches characters not in the class.                      var result = Regex .Replace(text, @"[^" + allowedPattern + "]", replacement);                      return result;              }static public string RemoveNonAlphanumericCharacters( this string text)              {                      var result = text.ReplaceNotExpectedCharacters(NonAlphaNumericCharacters, "" );                      return result;              }        public const string NonAlphaNumericCharacters = "[a-zA-Z0-9]";There are a couple of functions from my StringHelper class  http://geekswithblogs.net/mnf/archive/2006/07/13/84942.aspx , that are used here.    //                           /// <summary>               /// 'StripBrackets checks that starts from sStart and ends with sEnd (case sensitive).               ///           'If yes, than removes sStart and sEnd.               ///           'Otherwise returns full string unchanges               ///           'See also MidBetween               /// </summary>               /// <param name="str"></param>               /// <param name="sStart"></param>               /// <param name="sEnd"></param>               /// <returns></returns>               public static string StripBrackets( this string str, string sStart, string sEnd)              {                      if (CheckBrackets(str, sStart, sEnd))                     {                           str = str.Substring(sStart.Length, (str.Length - sStart.Length) - sEnd.Length);                     }                      return str;              }               public static bool CheckBrackets( string str, string sStart, string sEnd)              {                      bool flag1 = (str != null ) && (str.StartsWith(sStart) && str.EndsWith(sEnd));                      return flag1;              }               public static string WrapBrackets( string str, string sStartBracket, string sEndBracket)              {                      StringBuilder builder1 = new StringBuilder(sStartBracket);                     builder1.Append(str);                     builder1.Append(sEndBracket);                      return builder1.ToString();              }v

    Read the article

  • SSIS Expression to Find Text Between Characters

    - by Compudicted
    It will be a super short and looks like the first and last post in January 2011. So back to the topic, I decided to share an SSIS expression I crafted to extract the value concealed between two characters (I needed to get a portion of text in a file path): Substring(@[User::MyString],FINDSTRING(@[User::MyString],"(",1)+1,FINDSTRING(@[User::MyString],")",1) - FINDSTRING(@[User::MyString],"(",1)-1) The value of MyString say could be c:\test\test(testing123456789).txt, then the resulting text captured testing123456789. Hopefully it will be needed to somebody.

    Read the article

  • Perl like regular expression in Oracle DB

    - by user13136722
    There's regular expression support in Oracle DB Using Regular Expressions in Database Applications Oracle SQL PERL-Influenced Extensions to POSIX Standard But '\b' is not supported which I believe is quite wideliy used in perl and/or other tools perlre - perldoc.perl.org \b Match a word boundary So, I experimented with '\W' which is non-"word" character When combined with beginning-of-line and end-of-line like below, I think it works exactly the same as '\b' SELECT * FROM TAB1 WHERE regexp_like(TEXTCOL1, '(^|\W)a_word($|\W)', 'i')

    Read the article

  • Expression Evaluator - Basic Level

    An expression evaluator that doesn't support parantheses at the beginning...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • In which order I had to simplify this Boolean expression?

    - by user3662105
    I have to simplify this Boolean expression but i quite found it difficult since don't know in which order had to start with. the expression is: (x iff y) or (y iff z) if x found it little complicated to simplify since i don't know the order do I have to write it like: ((x iff y) or (y iff z)) if x or: (x iff y) or ((y iff z) if x) if you can give me a spot on this section of Boolean algebra. and I really will appreciate it if you gave me steps on how to simplify it. and had to say that I already tried a lot, solved a lot, tried wolfram alpha and others too even compared the results using truth tables but get different results and didn't know the right one from them. thanks in advance for your helping

    Read the article

  • How can I use a config-file in Expression Blend 4?

    - by sofri
    Hi, while trying to use the "InfoStrat"-Bing-Maps-Control in Expression Blend 4 for my Surface Application, I get the error message: "Mixed mode assembly is built against version v2.0.50527 of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information" I already found out that I need to write this configfile: <configuration> <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0"/> </startup> </configuration> But Expression Blend doesn't seem to recognize that it is there. So how can I solve this problem?

    Read the article

  • Scala parser combinator runs out of memory

    - by user3217013
    I wrote the following parser in Scala using the parser combinators: import scala.util.parsing.combinator._ import scala.collection.Map import scala.io.StdIn object Keywords { val Define = "define" val True = "true" val False = "false" val If = "if" val Then = "then" val Else = "else" val Return = "return" val Pass = "pass" val Conj = ";" val OpenParen = "(" val CloseParen = ")" val OpenBrack = "{" val CloseBrack = "}" val Comma = "," val Plus = "+" val Minus = "-" val Times = "*" val Divide = "/" val Pow = "**" val And = "&&" val Or = "||" val Xor = "^^" val Not = "!" val Equals = "==" val NotEquals = "!=" val Assignment = "=" } //--------------------------------------------------------------------------------- sealed abstract class Op case object Plus extends Op case object Minus extends Op case object Times extends Op case object Divide extends Op case object Pow extends Op case object And extends Op case object Or extends Op case object Xor extends Op case object Not extends Op case object Equals extends Op case object NotEquals extends Op case object Assignment extends Op //--------------------------------------------------------------------------------- sealed abstract class Term case object TrueTerm extends Term case object FalseTerm extends Term case class FloatTerm(value : Float) extends Term case class StringTerm(value : String) extends Term case class Identifier(name : String) extends Term //--------------------------------------------------------------------------------- sealed abstract class Expression case class TermExp(term : Term) extends Expression case class UnaryOp(op : Op, exp : Expression) extends Expression case class BinaryOp(op : Op, left : Expression, right : Expression) extends Expression case class FuncApp(funcName : Term, args : List[Expression]) extends Expression //--------------------------------------------------------------------------------- sealed abstract class Statement case class ExpressionStatement(exp : Expression) extends Statement case class Pass() extends Statement case class Return(value : Expression) extends Statement case class AssignmentVar(variable : Term, exp : Expression) extends Statement case class IfThenElse(testBody : Expression, thenBody : Statement, elseBody : Statement) extends Statement case class Conjunction(left : Statement, right : Statement) extends Statement case class AssignmentFunc(functionName : Term, args : List[Term], body : Statement) extends Statement //--------------------------------------------------------------------------------- class myParser extends JavaTokenParsers { val keywordMap : Map[String, Op] = Map( Keywords.Plus -> Plus, Keywords.Minus -> Minus, Keywords.Times -> Times, Keywords.Divide -> Divide, Keywords.Pow -> Pow, Keywords.And -> And, Keywords.Or -> Or, Keywords.Xor -> Xor, Keywords.Not -> Not, Keywords.Equals -> Equals, Keywords.NotEquals -> NotEquals, Keywords.Assignment -> Assignment ) def floatTerm : Parser[Term] = decimalNumber ^^ { case x => FloatTerm( x.toFloat ) } def stringTerm : Parser[Term] = stringLiteral ^^ { case str => StringTerm(str) } def identifier : Parser[Term] = ident ^^ { case value => Identifier(value) } def boolTerm : Parser[Term] = (Keywords.True | Keywords.False) ^^ { case Keywords.True => TrueTerm case Keywords.False => FalseTerm } def simpleTerm : Parser[Expression] = (boolTerm | floatTerm | stringTerm) ^^ { case term => TermExp(term) } def argument = expression def arguments_aux : Parser[List[Expression]] = (argument <~ Keywords.Comma) ~ arguments ^^ { case arg ~ argList => arg :: argList } def arguments = arguments_aux | { argument ^^ { case arg => List(arg) } } def funcAppArgs : Parser[List[Expression]] = funcEmptyArgs | ( Keywords.OpenParen ~> arguments <~ Keywords.CloseParen ^^ { case args => args.foldRight(List[Expression]()) ( (a,b) => a :: b ) } ) def funcApp = identifier ~ funcAppArgs ^^ { case funcName ~ argList => FuncApp(funcName, argList) } def variableTerm : Parser[Expression] = identifier ^^ { case name => TermExp(name) } def atomic_expression = simpleTerm | funcApp | variableTerm def paren_expression : Parser[Expression] = Keywords.OpenParen ~> expression <~ Keywords.CloseParen def unary_operation : Parser[String] = Keywords.Not def unary_expression : Parser[Expression] = operation(0) ~ expression(0) ^^ { case op ~ exp => UnaryOp(keywordMap(op), exp) } def operation(precedence : Int) : Parser[String] = precedence match { case 0 => Keywords.Not case 1 => Keywords.Pow case 2 => Keywords.Times | Keywords.Divide | Keywords.And case 3 => Keywords.Plus | Keywords.Minus | Keywords.Or | Keywords.Xor case 4 => Keywords.Equals | Keywords.NotEquals case _ => throw new Exception("No operations with this precedence.") } def binary_expression(precedence : Int) : Parser[Expression] = precedence match { case 0 => throw new Exception("No operation with zero precedence.") case n => (expression (n-1)) ~ operation(n) ~ (expression (n)) ^^ { case left ~ op ~ right => BinaryOp(keywordMap(op), left, right) } } def expression(precedence : Int) : Parser[Expression] = precedence match { case 0 => unary_expression | paren_expression | atomic_expression case n => binary_expression(n) | expression(n-1) } def expression : Parser[Expression] = expression(4) def expressionStmt : Parser[Statement] = expression ^^ { case exp => ExpressionStatement(exp) } def assignment : Parser[Statement] = (identifier <~ Keywords.Assignment) ~ expression ^^ { case varName ~ exp => AssignmentVar(varName, exp) } def ifthen : Parser[Statement] = ((Keywords.If ~ Keywords.OpenParen) ~> expression <~ Keywords.CloseParen) ~ ((Keywords.Then ~ Keywords.OpenBrack) ~> statements <~ Keywords.CloseBrack) ^^ { case ifBody ~ thenBody => IfThenElse(ifBody, thenBody, Pass()) } def ifthenelse : Parser[Statement] = ((Keywords.If ~ Keywords.OpenParen) ~> expression <~ Keywords.CloseParen) ~ ((Keywords.Then ~ Keywords.OpenBrack) ~> statements <~ Keywords.CloseBrack) ~ ((Keywords.Else ~ Keywords.OpenBrack) ~> statements <~ Keywords.CloseBrack) ^^ { case ifBody ~ thenBody ~ elseBody => IfThenElse(ifBody, thenBody, elseBody) } def pass : Parser[Statement] = Keywords.Pass ^^^ { Pass() } def returnStmt : Parser[Statement] = Keywords.Return ~> expression ^^ { case exp => Return(exp) } def statement : Parser[Statement] = ((pass | returnStmt | assignment | expressionStmt) <~ Keywords.Conj) | ifthenelse | ifthen def statements_aux : Parser[Statement] = statement ~ statements ^^ { case st ~ sts => Conjunction(st, sts) } def statements : Parser[Statement] = statements_aux | statement def funcDefBody : Parser[Statement] = Keywords.OpenBrack ~> statements <~ Keywords.CloseBrack def funcEmptyArgs = Keywords.OpenParen ~ Keywords.CloseParen ^^^ { List() } def funcDefArgs : Parser[List[Term]] = funcEmptyArgs | Keywords.OpenParen ~> repsep(identifier, Keywords.Comma) <~ Keywords.CloseParen ^^ { case args => args.foldRight(List[Term]()) ( (a,b) => a :: b ) } def funcDef : Parser[Statement] = (Keywords.Define ~> identifier) ~ funcDefArgs ~ funcDefBody ^^ { case funcName ~ funcArgs ~ body => AssignmentFunc(funcName, funcArgs, body) } def funcDefAndStatement : Parser[Statement] = funcDef | statement def funcDefAndStatements_aux : Parser[Statement] = funcDefAndStatement ~ funcDefAndStatements ^^ { case stmt ~ stmts => Conjunction(stmt, stmts) } def funcDefAndStatements : Parser[Statement] = funcDefAndStatements_aux | funcDefAndStatement def parseProgram : Parser[Statement] = funcDefAndStatements def eval(input : String) = { parseAll(parseProgram, input) match { case Success(result, _) => result case Failure(m, _) => println(m) case _ => println("") } } } object Parser { def main(args : Array[String]) { val x : myParser = new myParser() println(args(0)) val lines = scala.io.Source.fromFile(args(0)).mkString println(x.eval(lines)) } } The problem is, when I run the parser on the following example it works fine: define foo(a) { if (!h(IM) && a) then { return 0; } if (a() && !h()) then { return 0; } } But when I add threes characters in the first if statement, it runs out of memory. This is absolutely blowing my mind. Can anyone help? (I suspect it has to do with repsep, but I am not sure.) define foo(a) { if (!h(IM) && a(1)) then { return 0; } if (a() && !h()) then { return 0; } } EDIT: Any constructive comments about my Scala style is also appreciated.

    Read the article

  • Automated capturing of screen using "Microsoft Expression Encoder Screen Capture" command line operations

    - by gentlesea
    I want to capture screen output automatically from within my TestComplete test program. For this i found the free limited version of "Microsoft Expression Encoder Screen Capture" which I want to automate. Is there a separate command line interface for Microsoft Expression Encoder Screen Capture or do I have to use the command line interface for Expression Studio? I found this options: http://msdn.microsoft.com/en-us/library/cc294683.aspx. But before I dig deeper, I want to know if I am on the right way.

    Read the article

  • Confused about Huffman Trees

    - by ShrimpCrackers
    A quick tutorial on generating a huffman tree Confused about Huffman Trees. Near the end of that link above, it shows the tree with 2 elements left, and then the completed tree. I'm confused about the way that it is branched. Is there a specific way a huffman tree needs to be branched? For example, 57:* with its right child 35:* is branched off to the right. Could it have been 35 branched to the left with 22 branched to the right? Also, why wasn't 22:* paired up with 15:4 - it just paired with 20:5 to create a new tree. From initial obersvations it seems the tree does not need to be balanced or have any specific order other than that the frequencies of a leaf add up to the value of the parent node. Could two people creating a huffman tree with the same data end up with different encoding values?

    Read the article

  • Algorithm for evaluating nested logical expression

    - by TravelingSalesman
    I have a logical expression that I would like to evaluate. The expression can be nested and consists of T (True) or F (False) and parenthesis. The parenthesis "(" means "logical OR". Two terms TF beside each others (or any other two combinations beside each others), should be ANDED (Logical AND). For example, the expression: ((TFT)T) = true I need an algorithm for solving this problem. I thought of converting the expression first to disjunctive or conjunctive normal form and then I can easily evaluate the expression. However, I couldn't find an algorithm that normalizes the expression. Any suggestions? Thank you. The problem statement can be found here: https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=2&category=378&page=show_problem&problem=2967

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >