为什么此定义不涵盖所有模式情况? [英] Why doesn't this definition cover all pattern cases?

查看:74
本文介绍了为什么此定义不涵盖所有模式情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试triplize一个元素,即制作该元素的其他2个副本.

So I'm trying to triplize an element, i.e. making 2 other copies of the element.

所以我写了这个:

triplize :: [a] -> [a]
triplize [x] = concatMap (replicate 3) [x]

但是我一直收到这个错误:

But I've been getting this error:

Non-exhaustive patterns in function triplize

我是Haskell的新手,所以希望您能提出任何建议!

I'm new to Haskell, so any pointers are appreciated!

推荐答案

撰写时

triplize [x]

您是说参数必须与模式[x]相匹配.此模式表示具有单个值的列表,该列表将分配给名称x.请注意,列表不会分配给名称x,只会分配给该列表中的单个值.如果您尝试使用列表[][1, 2]调用函数,则会导致错误,因为您尚未告诉函数如何处理这些输入.

You are saying that the argument must match the pattern [x]. This pattern represents a list with a single value, which will be assigned to the name x. Note that the list will not be assigned to the name x, only the single value in that list. If you tried calling your function with the list [] or [1, 2], it would cause an error because you haven't told your function what to do with those inputs.

您可能想要的是

triplize x = concatMap (replicate 3) x

这里的模式只是x,它与任何列表匹配,从空列表到无限列表.请注意,函数定义中的模式与您自己创建值的方式匹配.在Haskell中,您可以在构造函数上进行模式匹配,并且列表可以使用方括号和逗号来构造,或者可以使用:运算符(即[1, 2, 3] == (1:2:3:[]))来构造它们.实际上,:运算符就是Haskell在内部表示列表的方式.

Here your pattern is just x, which matches any list, from the empty list to an infinite list. Notice that the patterns in your function definition match the way you make the values themselves. In Haskell you can pattern match on constructors, and lists can be constructed with square brackets and commas, or they can be constructed using the : operator, so [1, 2, 3] == (1:2:3:[]). In fact, the : operator is how Haskell represents lists internally.

使用更多模式匹配的示例:

An example that uses more pattern matches:

sumSuccessive :: [Int] -> [Int]
sumSuccessive [] = []      -- Empty list
sumSuccessive [x] = [x]    -- Singleton list (only one value)
sumSuccessive (x:y:rest) = x + y : sumSuccessive rest
    -- Match a list with at least two elements `x` and `y`,
    -- with the rest of the list assigned to the name `rest`

此示例函数将获取列表[1, 2, 3, 4]并返回列表[3, 7]([1 + 2, 3 + 4]).

This example function would take the list [1, 2, 3, 4] and return the list [3, 7] ([1 + 2, 3 + 4]).

这篇关于为什么此定义不涵盖所有模式情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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