Why can't I map a pattern in the concatenation (++) function in Haskell?

I am trying to map a pattern **String Newline String** in a Split function.

 split::String -> [String] split[] = [] split (x++'\n':xs) = [x]++split(xs) 

I get this error: Parse error in pattern: x ++ ('\n' : xs)

What am I doing wrong here?

I know that there are other ways to achieve the same result, but I would like to understand what is wrong with this template. I am new to Haskell BTW.

+5
source share
2 answers

One of the problems (as I understand it) is that ++ not a list data type constructor in a way : You may think that the list data type is defined as

 data [a] = [] | a : [a] 

Where : - a constructor that adds elements to the top of the 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 list of data types, for example

 data List a = Empty | Cons a (List a) 

This would mimic the behavior of our familiar list. In fact, you can use (Cons val) in the template. I believe that you can also define a type with a concat constructor this way

 data CList a = Empty | Cons a (CList a) | Concat (CList a) (CList a) 

What you can use to lazily combine two lists and defer joining them to one. With this type of data, you could match the match with Concat xs ys input, but you would only work on the border of two lists, not in the middle of one.

Anyway, I'm still pretty new to Haskell, but hope this is in place.

+11
source

Imagine you could. Then matching "a\nb\nc" can lead to x = "a", xs = "b\nc" or x = "a\nb", xs = "c" , and you need a specific ad hoc rule to solve what to use. Matching functions is also impossible to intelligently implement as a whole: you need to find x given fx , and there is no way to do this except to try all possible x .

+5
source

Source: https://habr.com/ru/post/1237906/


All Articles