我有一个Haskell,包含字符串作为键,一些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
..。对我没多大帮助。
有什么建议吗?谢谢!
发布于 2011-01-06 04:46:01
查找是lookup :: Ord k => k -> Map k a -> Maybe a
类型的。结果封装在一个可能的指示键可能不存在于映射中。
下面是一种可行的方法:
runOp :: String -> a -> a -> b
runOp key x y = case lookup key ops of
Just op -> op x y
Nothing -> error ("Couldn't find operator: " ++ key)
如果密钥不存在,这将是最低的。您还可以从Either
返回Maybe
或runOp结果,以适应密钥不存在的可能性,但这取决于您。
可能定义如下:
data Maybe a = Just a | Nothing
也就是说,它要么保存一个结果值,要么保存一个空值。像一个存在主义哲学家,哈斯克尔强迫你承认Nothing
的可能性。
发布于 2011-01-06 04:09:09
首先,您显示的错误不是由您显示的代码造成的。代码会导致以下错误(在ghc中):
Couldn't match expected type `t1 -> t2 -> t'
against inferred type `Data.Maybe.Maybe
该错误是由lookup
返回一个Maybe
这一事实造成的。因此,您需要首先展开Maybe
。
发布于 2011-01-06 07:52:35
import Control.Applicative
ops :: (Fractional a) => Map.Map String (a -> a -> a)
ops = Map.fromList [("+", (+)),
("-", flip (-)),
("*", (*)),
("/", flip (/))]
apply :: (Fractional a) => String -> a -> a -> Maybe a
apply op x y = Map.lookup op ops <*> y <*> x
因为lookup
返回一个Maybe a
(在本例中是Maybe (a -> a -> a)
),所以无法将其直接应用于a
。我们可以使用<*>
将LHS从mote中提取出来,将其应用于RHS,并将其注入monad中。(或者像Bill那样手工操作。)
https://stackoverflow.com/questions/4614662
复制相似问题