Haskell pattern matching char in a string

懵懂的女人 提交于 2020-12-12 11:54:06

问题


I have a question on pattern matching:

Is it possible to somehow match a (string ++ [char] ++ anotherstring)?

I have tried something like:

f (s++";"++r) = s++r (the rhs is trivial, but its just for testing ;))

But this results in a parse error.


回答1:


No, it's not possible. Pattern matching deconstructs values according to the constructors they were built with, so you can only use constructor applications in pattern matching to describe which values match the pattern and which don't.

For something like your example, a case works well,

f str = case break (== ';') str of
          (s, _:r) -> s ++ r
          _        -> error "No semicolon found"



回答2:


For completeness' sake, one could make gratuitous use of GHC's ViewPatterns extension, and rewrite Daniel Fischer's example as something like:

{-# LANGUAGE ViewPatterns #-}

f (break (== ';') -> (s, _:r)) = s ++ r
f _ = error "No semicolon found"

This is of course a purely cosmetic change, but if you prefer the usual "group of equations" syntax instead of case expressions, there it is.

N.B. -- I don't have GHC at hand right now so I haven't actually tested the above.




回答3:


No it is not possible. There are many functions in split which you can use to accomplish what you are trying to do.




回答4:


You can do this kind of pattern matching similar to the way proposed here:

Haskell pattern matching conundrum



来源:https://stackoverflow.com/questions/64944929/pattern-match-with-strings-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!