2017-11-10 50 views
0

我想在Haskell中做一個計算器。我已經做到了可以接受兩個參數的地步。但是我被困在可能需要兩個以上論點的地步。例如,該輸入類型是(+ 1 2)和它打印3.但現在應能採取在(+ 1 2 3),並打印出6.建立一個Haskell計算器,可以採用兩個以上的參數

的代碼是在這裏:

import System.IO 

main = do loop [] 

leadingNonSpaces [] = 0 
leadingNonSpaces (' ':cs) = 0 
leadingNonSpaces (c:cs) = 1 + (leadingNonSpaces cs) 

keepNonSpaces cs = take (leadingNonSpaces cs) cs 

firstWord cs = keepNonSpaces cs 

second x = head (drop 1 x) 

-- evaluation loop, taking list of defined variables (var, value) tuples 
-- reads a statement and prints out its value 
loop vars = do 
    eof <- isEOF 
    if eof 
    then return() 
    else do line <- getLine 
      if ((firstWord line) == "set") 
       then do 
       let tokens = (drop 1 (tokenize line)) 
       let value = (eval vars (second tokens)) 
       putStrLn (show value) 
       loop (((head tokens),value):vars) 
       else do 
       let res = eval vars line 
       putStrLn (show res) 
       loop vars 

-- split string into space-separated tokens, but counting 
-- a parenthesized subexpression as a single token 
tokenize [] = [] 
tokenize (' ':cs) = tokenize cs 
tokenize cs = let i = charsInToken cs 
    in (take i cs):(tokenize (drop i cs)) 

-- returns # characters in first token; counts parenthesized 
-- expression as a single token 
charsInToken str = helper str 0 
    -- helper takes string and number of open parentheses to be matched 
    -- returns number of chars in first token 
    where helper [] 0 = 0 
     helper (' ':cs) 0 = 0 
     helper (' ':cs) d = 1 + (helper cs d) 
     helper ('(':cs) d = 1 + (helper cs (d+1)) 
--  helper (')':cs) 1 = 1    -- correct, but unnecessary 
     helper (')':cs) d = 1 + (helper cs (d-1)) 
     helper (c:cs) d = 1 + (helper cs d) 

-- evaluates expression in its argument string, returning an int 
-- first argument is list of (var, value) tuples for declared variables 
eval vars ('(':cs) = eval vars (take ((length cs)-1) cs) 
eval vars (c:cs) = if (elem c "") 
       then read (c:cs) :: Int 
       else let ts = tokenize (c:cs) 
       in if (elem (head (head ts)) "+-*/") 
        then apply_op (head ts) (map (eval vars) (drop 1 ts)) 
        else lookupVar vars (head ts) 

-- look up a variable in the list of (variable, value) tuples and 
-- return corresponding value 
lookupVar [] v = error ("Undefined variable: " ++ v) 
lookupVar ((var,val):ts) v = if(v == var) 
          then val 
          else lookupVar ts v 

-- apply an operator to a list of two integers 
apply_op "+" [arg1, arg2] = arg1 + arg2 
apply_op "-" [arg1, arg2] = arg1 - arg2 
apply_op "*" [arg1, arg2] = arg1 * arg2 
apply_op "/" [arg1, arg2] = div arg1 arg2 
+0

你試圖自己解決這個問題? –

回答

0

更改應用程序可能會有所幫助。這裏有兩個例子:

apply_op 「+」 xs = sum xs 
apply_op 「-「 [x] = -x 
apply_op 「-「 (x:[email protected](_:_)) = x - sum xs 
相關問題