4

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.

Stackd
  • 683
  • 1
  • 6
  • 12
  • 1
    I just wanted to point out that a string containing multiple semicolons would make this ambiguous. The solutions below assume you want to match the first semicolon, but in general, such a function would be non-deterministic, and should return a possibly empty list of results. – pat Oct 25 '12 at 07:16

4 Answers4

9

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"
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • 4
    This question is asking for something that's almost a `String` literal counterpart to n+k patterns, the latter being a feature which was recently *removed* from the language. So not only is it impossible, the possibility of it becoming not-impossible is getting steadily less possible. Er, possibly. – C. A. McCann Oct 24 '12 at 18:59
4

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.

C. A. McCann
  • 76,893
  • 19
  • 209
  • 302
1

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

Satvik
  • 11,238
  • 1
  • 38
  • 46
1

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

Haskell pattern matching conundrum

Community
  • 1
  • 1
Marius Danila
  • 10,311
  • 2
  • 34
  • 37