在haskell函数中使用regexp
我想写一个Haskell函数,它的行为依赖于匹配其中一个参数的正则表达式模式。在C/Python/Perl这样的语言中,我肯定只会使用一个大的if/else结构,但实际上我没有这个选项。Haskell最惯用的处理方法是什么 我考虑过保护,但它们不起作用:在haskell函数中使用regexp,regex,haskell,idioms,Regex,Haskell,Idioms,我想写一个Haskell函数,它的行为依赖于匹配其中一个参数的正则表达式模式。在C/Python/Perl这样的语言中,我肯定只会使用一个大的if/else结构,但实际上我没有这个选项。Haskell最惯用的处理方法是什么 我考虑过保护,但它们不起作用:没有(Data.String.IsString source0)的实例。: case构造中使用的模式匹配如果能够处理Regex,将是完美的 function arg = case arg of (pattern1 match) -> d
没有(Data.String.IsString source0)的实例。
:
case构造中使用的模式匹配如果能够处理Regex,将是完美的
function arg = case arg of
(pattern1 match) -> dothis match
(pattern2 match) -> dothat match
_ -> failwith arg
你的第一个例子对我很有用:
import Text.Regex.Posix
function :: String -> String
function arg
| arg =~ "pattern1" = "1"
| arg =~ "pattern2" = "2"
| otherwise = "3"
我认为您的IsString
错误是由于字符串文本扩展超载造成的。尝试禁用该选项,或者尝试使用显式String
字符串:
function :: String -> String
function arg
| arg =~ ("pattern1"::String) = "1"
| arg =~ ("pattern2"::String) = "2"
| otherwise = "3"
太吵了?你可以把拐杖推到最后一行
function2 :: String -> String
function2 arg
| arg =~ s"pattern1" = "1"
| arg =~ s"pattern2" = "2"
| otherwise = "3"
where s :: String -> String
s = id
需要分组匹配吗
function3 :: String -> String
function3 arg
| [_,x]:_ <- arg =~ s"pat(t*)ern1" = "matched group: " ++ x
-- ...
function3::String->String
函数3参数
|[\ux]:\在使用gaurds的版本中,您可能需要显式的类型注释,例如function::String->ReturnType
PatternGuards
是标准的,不需要pragmaViewPatterns
可能更接近OP所要求的,或者更新颖的Patterns同义词
@matejcik,因为=~
有许多重载,包括一个列表返回列表,我在这里利用了这些重载。我不记得所有的细节,因为我在3年前回答了这个问题,但是图书馆的文档应该包含它们。谢谢你的回答,这很有帮助!(虽然对于功能3
表单,我总是看到第一个守卫匹配,即使匹配是空的。)
function3 :: String -> String
function3 arg
| [_,x]:_ <- arg =~ s"pat(t*)ern1" = "matched group: " ++ x
-- ...