Recent

Author Topic: split math expresion into tokens  (Read 2137 times)

madskiba

  • Newbie
  • Posts: 1
split math expresion into tokens
« on: July 24, 2017, 01:47:14 am »
how to saparete this '5+85*5/-1-106^0.15'.

and the result
'5' , '+' , '85' , '*' , '5' , '/' , '-1' ,  '-' , '106' , '^' , '0.15'

Phil

  • Hero Member
  • *****
  • Posts: 2737
Re: split math expresion into tokens
« Reply #1 on: July 24, 2017, 01:51:00 am »
how to saparete this '5+85*5/-1-106^0.15'.

and the result
'5' , '+' , '85' , '*' , '5' , '/' , '-1' ,  '-' , '106' , '^' , '0.15'

If you need to parse the expression in order to evaluate it, try this:

http://wiki.lazarus.freepascal.org/How_To_Use_TFPExpressionParser

Leledumbo

  • Hero Member
  • *****
  • Posts: 8757
  • Programming + Glam Metal + Tae Kwon Do = Me
Re: split math expresion into tokens
« Reply #2 on: July 24, 2017, 06:23:08 am »
The proper way is to build a parser, first part of Prof. Wirth book should help, but it's geared more toward in-class use. Otherwise Jack Crenshaw's articles is more practical, but is not really structured. Last but not least, if you think proper parsing is too complex to understand, you can always fallback to System.Copy, System.Delete, System.Pos, etc. but for me it's too cumbersome compared to time spent to understand parsing properly (it's also future proof for your skill).

marcov

  • Administrator
  • Hero Member
  • *
  • Posts: 11452
  • FPC developer.
Re: split math expresion into tokens
« Reply #3 on: July 24, 2017, 07:03:14 am »
Unit symbolic (that comes with Free Pascal) contains an expression evaluator. The tokenizer can return a tree form, or reduce that to RPN. (but that is string form again).


Thaddy

  • Hero Member
  • *****
  • Posts: 14373
  • Sensorship about opinions does not belong here.
Re: split math expresion into tokens
« Reply #4 on: July 24, 2017, 08:45:46 am »
There's also the TParser class that can be used to do that. I once wrote a solver for simple math operations using that for an intermediate pascal course.
I'll see if I can find it. (Borland used the same example based on mine at the time, so maybe it is still available on the Embarcadero website?)).
It also depends on what OP wants: if he is a computer science student I would go for lex/yacc or Bison or Goldparser and use a parser generator.
Otherwise I would use TParser, but Marco's code is also fine.
Object Pascal programmers should get rid of their "component fetish" especially with the non-visuals.

 

TinyPortal © 2005-2018