我想知道是否可以在这种情况下使用方法代替常量:
fromEvent :: Event -> Maybe WorkspaceCreated
fromEvent event =
case (eventName $ header event) of
"workspaceCreated" -> Just WorkspaceCreated {eventId = CoreEvent.eventId $ header event, workspaceId = aggregateId $ header event}
_ -> Nothing
类似这样:
eventNameForWorkspaceCreated = "workspaceCreated" :: String
fromEvent :: Event -> Maybe WorkspaceCreated
fromEvent event =
case (eventName $ header event) of
eventNameForWorkspaceCreated -> Just WorkspaceCreated {eventId = CoreEvent.eventId $ header event, workspaceId = aggregateId $ header event}
_ -> Nothing
在最后一个示例中,使用eventNameForWorkspaceCreated作为有意义的变量名称...
答案 0 :(得分:1)
不直接。名称被视为不可辩驳的模式;名称的值不用作匹配的模式。
相反,您可以使用PatternSynonyms
扩展名定义模式同义词。
{-# LANGUAGE PatternSynonyms -#}
pattern EventNameForWorkspaceCreated = "workspaceCreated"
fromEvent :: Event -> Maybe WorkspaceCreated
fromEvent event = case (eventName $ header event) of
EventNameForWorkspaceCreated -> Just WorkspaceCreated {eventId = CoreEvent.event}
_ -> Nothing
但是,如果您实际上不需要模式匹配,则保护语法可能会更简单。 (可以比较String
个值是否相等。)
fromEvent event | eventName $ header event == eventNameForWorkspaceCreated = Just WorkspaceCreated {eventId = CoreEvent.event}
| otherwise = Nothing