Last active
October 6, 2018 22:13
-
-
Save SYZYGY-DEV333/ea3f5eeb3473927c8faa294bb72a8858 to your computer and use it in GitHub Desktop.
Infix to Pre- or Postfix in GNU Smalltalk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Object subclass: Conversion [ | |
isOperator: c [ | |
(c isAlphaNumeric) ifFalse: [ ^true ]. | |
(c isAlphaNumeric) ifTrue: [ ^false ]. | |
] | |
getPriority: char [ | |
(char = $-) ifTrue: [ ^1 ]. | |
(char = $+) ifTrue: [ ^1 ]. | |
(char = $/) ifTrue: [ ^2 ]. | |
(char = $*) ifTrue: [ ^2 ]. | |
(char = $^) ifTrue: [ ^3 ]. | |
^0. | |
] | |
infixToPostfix: infixString [ | |
|infix l char_stack output| | |
infix := ('(', infixString,')') asArray. | |
l := infix size. | |
char_stack := #(). | |
output := ''. | |
1 to: l do: [:i | | |
((infix at: i) isAlphaNumeric) ifTrue: [ | |
output := output, ((infix at: i) asString). | |
] ; ifFalse: [ | |
((infix at: i) = $() ifTrue: [ | |
char_stack := #($)), char_stack. | |
] ; ifFalse: [ | |
((infix at: i) = $)) ifTrue: [ | |
[(char_stack at: 1) = $(] whileFalse: [ | |
output := output, (char_stack at: 1) asString. | |
char_stack := char_stack allButFirst. | |
]. | |
char_stack := char_stack allButFirst. | |
] ; ifFalse: [ | |
(self isOperator: (char_stack at: 1)) ifTrue: [ | |
[(self getPriority: (infix at: i)) <= | |
(self getPriority: (char_stack at: 1))] whileTrue: [ | |
output := output, (char_stack at: 1) asString. | |
char_stack := char_stack allButFirst. | |
]. | |
char_stack := ((infix at: i) asString) asArray, char_stack. | |
]]]]. | |
]. | |
^output. | |
] | |
infixToPrefix: infixStr [ | |
|infix l prefix| | |
infix := infixStr asArray. | |
l := infix size. | |
prefix := ''. | |
infix := infix reverse. | |
1 to: l do: [:i | | |
((infix at: i) = $() ifTrue: [ | |
infix at: i put: $). | |
] ; ifFalse: [ | |
((infix at: i) = $)) ifTrue: [ | |
infix at: i put: $(. | |
]]. | |
]. | |
prefix := self infixToPostfix: (infix asString). | |
prefix := prefix reverse. | |
^prefix. | |
] | |
] | |
Eval [ | |
|s out| | |
s := '(a-b/c)*(a/k-l)'. | |
out := (Conversion new) infixToPostfix: s. | |
out printNl. | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment