我有一個Haskell映射,包含字符串作爲鍵和一些lambda函數作爲項。 例如:將運營商與lambda函數關聯的映射
-- List of supported Operators -> mapping with functions
ops = Map.fromList [("+", \x y -> x + y),
("-", \x y -> y - x),
("*", \x y -> x * y),
("/", \x y -> y/x)]
我想要寫一個函數,它作爲輸入:
- 表示操作者的字符串[ 「+」, 「 - 」, 「*」, 「/」]
- 兩個數字
基於運營商和OPS映射,函數將計算總和/減法/等。這兩個數字。
我已經試過類似:
(Map.lookup "+" a) 1 2
但它不工作。
的錯誤是:
Top level:
No instance for (Show (Integer -> Integer))
arising from use of `print' at Top level
Probable fix: add an instance declaration for (Show (Integer
In a 'do' expression: print it
<interactive>:1:1:
No instance for (Monad ((->) t))
arising from use of `Data.Map.lookup' at <interactive>:1:1-
Probable fix: add an instance declaration for (Monad ((->) t)
In the definition of `it': it = (Data.Map.lookup "+" a) 1 2
...對我來說不是非常有幫助。
有什麼建議嗎?謝謝 !
請注意,您可以執行`[(「+」,(+)),(「 - 」,( - )),...](parens中的操作符被稱爲section,並且與你的lambdas更加整齊地做同樣的事情;它也適用於函數的中綴應用,並且當任一參數是固定的,例如`(\`mod \`2)`或' (2 /)`)。 – delnan 2011-01-06 12:15:44
@delnan雖然他有`-`和`/`這樣的「錯誤」方法。 – dave4420 2011-01-06 12:57:12