在haskell函数保护中使用regexp

Quy*_*uyk 9 regex haskell idioms

我想编写一个Haskell函数,其行为依赖于匹配其中一个参数的正则表达式模式.在像C/Python/Perl这样的语言中,我肯定会使用一个大的if/else结构,但我真的没有那个选项.什么是最惯用的Haskell处理方法?

我考虑过警卫,但他们没有工作No instance for (Data.String.IsString source0):

function arg
  | arg =~ "pattern1" = dothis arg
  | arg =~ "pattern2" = dothat arg
  | otherwise = failwith arg
Run Code Online (Sandbox Code Playgroud)

如果处理正则表达式,在案例结构中使用的模式匹配将是完美的.

function arg = case arg of
  (pattern1 match) -> dothis match
  (pattern2 match) -> dothat match
  _ -> failwith arg
Run Code Online (Sandbox Code Playgroud)

chi*_*chi 13

你的第一个例子并不为我工作:

import Text.Regex.Posix

function :: String -> String
function arg
  | arg =~ "pattern1" = "1"
  | arg =~ "pattern2" = "2"
  | otherwise = "3"
Run Code Online (Sandbox Code Playgroud)

我认为您的IsString错误是由于重载的字符串文字扩展名.尝试禁用它,或者尝试使用显式String字符串:

function :: String -> String
function arg
  | arg =~ ("pattern1"::String) = "1"
  | arg =~ ("pattern2"::String) = "2"
  | otherwise = "3"
Run Code Online (Sandbox Code Playgroud)

太吵了?你可以把残骸推到最后一行.

function2 :: String -> String
function2 arg
  | arg =~ s"pattern1" = "1"
  | arg =~ s"pattern2" = "2"
  | otherwise = "3"
  where s :: String -> String
        s = id
Run Code Online (Sandbox Code Playgroud)

需要子组匹配吗?

function3 :: String -> String
function3 arg
  | [_,x]:_ <- arg =~ s"pat(t*)ern1" = "matched group: " ++ x
  -- ...
Run Code Online (Sandbox Code Playgroud)

function3 "patttern1",变量x将被绑定"tt".打开function3 "xyz",测试将失败,下一个分支将被尝试.

  • `PatternGuards`是标准的,不需要编译指示.`ViewPatterns`可能更接近OP所要求的,或者甚至更新的`PatternSynonyms`. (2认同)