为什么我无法在Haskell的串联函数(++)上进行模式匹配? [英] Why can't I pattern match on the concatenation function (++) in Haskell?

查看:57
本文介绍了为什么我无法在Haskell的串联函数(++)上进行模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在函数Split中匹配 ** String Newline String ** 模式.

I'm trying to match **String Newline String** pattern in a function Split.

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

我收到此错误:解析模式错误:x ++('\ n':xs)

我在这里做什么错了?

我知道还有其他方法可以达到相同的结果,但是我想了解这种模式有什么问题.我是Haskell BTW的新手.

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.

推荐答案

一个问题(据我了解)是 ++ 不是列表数据类型的构造方法:是.您可以想到将列表数据类型定义为

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)

这将模仿我们熟悉的列表的行为.实际上,您可以在模式中使用(Cons val).我相信您也可以像这样用concat构造函数定义类型

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)

您可以用来懒惰地连接两个列表,然后将它们推迟成一个列表.使用这种数据类型,您可以与 Concat xs ys 输入进行模式匹配,但是您只能在两个列表的边界上工作,而不能在一个列表的中间工作.

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.

无论如何,我对Haskell还是很陌生,但我希望这是正确的.

Anyway I'm still fairly new to Haskell myself but I hope this is on point.

这篇关于为什么我无法在Haskell的串联函数(++)上进行模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆