【发布时间】:2011-01-06 11:58:45
【问题描述】:
我有一个 Haskell Map,包含字符串作为键和一些 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)]
我想写一个函数作为输入:
- 表示运算符 ["+", "-", "*", "/"] 的字符串
- 两个数字
根据算子和操作图,该函数将计算和/减/等。两个数字中的一个。
我尝试过类似的方法:
(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
...对我不是很有帮助。
有什么建议吗?谢谢!
【问题讨论】:
-
请注意,您可以只执行
[("+", (+)), ("-", (-)), ...](括号中的运算符称为一个部分,并且与您的 lambda 更简洁地执行相同的操作;它也适用于函数的中缀应用,并且当任一参数为固定,例如(`mod` 2)或(2/))。 -
@delnan 尽管他对
-和/提出异议,但这样做的“错误”方式。 -
@Dave:是的,我很傻。不过,不需要显式的 lambda:
flip (-)和flip (/):) -
感谢您的回答。最终我听从了比尔的建议,一切都如我所愿。