将运算符与lambda函数关联的映射

And*_*anu 3 lambda haskell map

我有一个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)]
Run Code Online (Sandbox Code Playgroud)

我想编写一个输入的函数:

  • 表示运算符的字符串["+"," - ","*","/"]
  • 两个数字

基于运算符和ops映射,函数将评估和/减/等.这两个数字.

我尝试过类似的东西:

(Map.lookup "+" a) 1 2
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

错误是:

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
Run Code Online (Sandbox Code Playgroud)

......对我没有多大帮助.

有什么建议 ?谢谢 !

Bil*_*ill 7

查找是类型lookup :: Ord k => k -> Map k a -> Maybe a.结果包含在一个Maybe中,表示该键可能不存在于地图中.

这是一种可行的方法:

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)
Run Code Online (Sandbox Code Playgroud)

如果密钥不存在,这将触底.您还可以从runOp 返回Either或返回Maybe结果,以适应密钥不存在的可能性,但这取决于您.

也许定义如下:

data Maybe a = Just a | Nothing
Run Code Online (Sandbox Code Playgroud)

也就是说,它要么保存结果值,要么保留空值.就像一位存在主义哲学家一样,哈斯克尔强迫你承认这种可能性Nothing.