问题
I'm trying to match **String Newline String**
pattern in a function Split.
split::String -> [String]
split[] = []
split (x++'\n':xs) = [x]++split(xs)
I'm getting this error:
Parse error in pattern: x ++ ('\n' : xs)
What am I doing wrong here?
I know there are other ways of achieving the same result but I'd like to understand what wrong with this pattern. I'm fairly new to Haskell BTW.
回答1:
One problem (as I understand it) is that ++
is not a constructor of the list data type the way :
is. You can think of the list data type being defined as
data [a] = [] | a : [a]
Where :
is a constructor that appends elements to the front of a list. However, ++
is a function (defined in the documentation here: http://hackage.haskell.org/package/base-4.8.1.0/docs/src/GHC.Base.html#%2B%2B) as
(++) :: [a] -> [a] -> [a]
(++) [] ys = ys
(++) (x:xs) ys = x : xs ++ ys
We could define our own data type list like
data List a = Empty | Cons a (List a)
That would mimic the behavior of our familiar list. In fact, you could use (Cons val)
in a pattern. I believe you could also define a type with a concat constructor like so
data CList a = Empty | Cons a (CList a) | Concat (CList a) (CList a)
Which you could use to lazily concatenate two lists and defer joining them into one. With such a data type you could pattern match against the Concat xs ys
input, but you that would only work on the boundary of two lists and not in the middle of one.
Anyway I'm still fairly new to Haskell myself but I hope this is on point.
回答2:
Imagine you could. Then matching "a\nb\nc"
could produce x = "a", xs = "b\nc"
or x = "a\nb", xs = "c"
and you'd need some ad hoc rule to decide which to use. Matching against functions is also impossible to reasonably implement in general: you need to find an x
given f x
, and there is no way to do this other than trying all possible x
.
来源:https://stackoverflow.com/questions/34217515/why-cant-i-pattern-match-on-the-concatenation-function-in-haskell