在列表的每个顶层元素周围包装[] [英] wraps [] around each top-level element of list

查看:68
本文介绍了在列表的每个顶层元素周围包装[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  wrap [1,2,3]应该输出[[1],[2],[3]] 
wrap [[1],[2],[ 3]]应输出[[[1]],[[2]],[[3]]]

我的实现是:

  wrap [] = [] 
wrap(x:xs)= [x ]:[wrap xs]

和haskell输出错误:发生检查:无法构造无限类型:预期类型:[t] - > [t]
实际类型:[t] - > [[t]]

p>

解决方案 包装 wrap xs 。你不想包装整个结果。您只想包装列表中其余部分的每个单独元素,这正是 wrap xs 已经做过的事情。因此, wrap 是:

  wrap :: [a]  - > ; [[a]] 
wrap [] = []
wrap(x:xs)= [x]:wrap xs

错误告诉你,你正在尝试使用 [t] ,其中GHC期望 t 。这正是我们上面所说的,你要包装太多次。


wrap [1,2,3] should output [[1],[2],[3]]
wrap [[1],[2],[3]] should output [ [[1]], [[2]], [[3]] ]

my implementation is:

wrap [] = []
wrap (x:xs) = [x] :  [wrap xs]

and haskell output an error: Occurs check: cannot construct the infinite type: t ~ [t]

Expected type: [t] -> [t] Actual type: [t] -> [[t]]

解决方案

[wrap xs] wraps the entire result of wrap xs. You don't want to wrap the entire result. You only want to wrap each individual element of the remainder of the list and that is exactly what wrap xs already does. Thus, wrap is:

wrap :: [a] -> [[a]]
wrap [] = []
wrap (x:xs) = [x] : wrap xs

The error is telling you that you are trying to use a [t] where GHC expects a t. This is exactly what we said above, that you are wrapping something too many times.

这篇关于在列表的每个顶层元素周围包装[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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