[英]How to use Data.Map ! Operator?
I have the following anti-pattern in my code:我的代码中有以下反模式:
existsFunc :: Maybe Item -> Item
This is part of a larger piece of code that checks if a name is in a Dictionary:这是检查名称是否在字典中的较大代码段的一部分:
genFunc :: InputType -> Item
genFunc input = existsFunc(Data.Map.lookup input (myDictionary))
existsFunc :: Maybe Item -> Item
existsFunc (Just x) = x
existsFunc Nothing = error "input missing from dictionary"
I would like to replace the above anti-pattern with with !我想用 with 替换上面的反模式! Map operator, but am having trouble understanding the syntax. 映射运算符,但无法理解语法。 How can the !怎么可能! be applied?被应用?
genFunc :: InputType -> Item
genFunc input = ! Data.Map.lookup input (myDictionary) Error: element not in the map
genFunc input = Data.Map.lookup input (myDictionary)
edit:编辑:
I also thought that it could be applied in the following way:我还认为它可以通过以下方式应用:
genFunc :: InputType -> Item
genFunc input = Data.Map.lookup input (myDictionary) ! input Error: element not in the map
genFunc input = Data.Map.lookup input (myDictionary)
Like this:像这样:
genFunc input = myDictionary Data.Map.! input
Usually people give a short name like M
to the Data.Map
module, using an import like:通常人们给Data.Map
模块起一个像M
这样的短名称,使用如下导入:
import qualified Data.Map as M
Then this shorter version is right:那么这个较短的版本是正确的:
genFunc input = myDictionary M.! input
Probably not even worth naming this function.可能甚至不值得命名这个函数。 Just use M.!
只需使用M.!
inline wherever you were gonna use genFunc
.在任何你要使用genFunc
的地方内联。
Keep in mind that !
请记住!
is exactly as much an antipattern as your existsFunc
.与您的existsFunc
完全一样的反模式。 So don't think you're fixing that here -- a real fix involves handling Nothing
from lookup
for real.所以不要认为你在这里解决了这个问题——真正的解决方法是真正处理lookup
中的Nothing
内容。 Each application's needs here vary;每个应用程序的需求各不相同; sometimes using a default value is correct, sometimes raising an error in some containing monad is correct, sometimes propagating the Maybe
into the caller's return type is correct, ...and half a dozen other responses exist out there, I'm sure.有时使用默认值是正确的,有时在某些包含 monad 中引发错误是正确的,有时将Maybe
传播到调用者的返回类型是正确的,......我敢肯定,还有六种其他响应存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.