I am working on a homework assignment and we have an array of mixed elements Char and Int.
I created this custom type:
data Element = CharToElement Char | IntToElement Int Which converts Chars and Ints into Elements so I can deal with them.
The issue I am having is what to do when I want to convert back?
So now that I do (head array) and that returns Element how do I convert that Element to an Int or Char.
This is for a postfix evaluator program.
Help is appreciated. Thanks.
Edit:
So I worked on it and this is what I have:
data Element = ElementConstructor (Char, Int, Bool) | IntToElement Int | CharToElement Char | NIL extractInt (_,i,_) = i extractChar (c,_,_) = c extractType (_,_,b) = b stack_push :: [Element] -> Element -> [Element] stack_push stack element = (element:stack) stack_pop :: [Element] -> [Element] stack_pop stack = (tail stack) stack_top :: [Element] -> Element stack_top stack = (head stack) postfix_eval eqn = (postfix_eval_rec (postfix_eval_const eqn []) []) postfix_eval_const eqn_raw eqn_conv = if null eqn_raw then NIL else if (isNumber (head eqn_raw)) then ElementConstructor(NIL, (head eqn_raw), True):eqn_conv else if (isAlpha (head eqn_raw)) then ElementConstructor((head eqn_raw), NIL, False):eqn_conv postfix_eval_const (tail eqn_raw) eqn_conv operate :: Element -> Element -> Element -> Element operate operator_char a b = if operator_char == '+' then IntToElement ( (extractInt a) + (extractInt b) ) else if operator_char == '-' then IntToElement ( (extractInt b) - (extractInt a) ) else if operator_char == '*' then IntToElement ( (extractInt a) * (extractInt b) ) else if operator_char == '/' then IntToElement ( (extractInt b) `div` (extractInt a) ) else IntToElement(0) postfix_eval_rec :: [Element] -> [Element] -> Int postfix_eval_rec eqn stack = if null eqn then (extractInt (stack_top stack)) else if ( (extractType (head eqn)) ) then (postfix_eval_rec (tail eqn) (stack_push stack (head eqn) ) ) else (postfix_eval_rec (tail stack) (stack_push (stack_pop (stack_pop stack)) (operate (head eqn) (stack_top stack) (stack_top (stack_pop stack))))) The idea is that you enter something like: postfix_eval [1,2,3,'+',4,'+','*'] and you get an answer in the form of an Int, in this case you get 9
getIntOrChar :: Element -> ???)