简体   繁体   English

将[]环绕列表的每个顶级元素

[英]wraps [] around each top-level element of list

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] 并haskell输出错误:发生检查:无法构造无限类型:t〜[t]

Expected type: [t] -> [t] Actual type: [t] -> [[t]] 预期类型:[t]-> [t]实际类型:[t]-> [[t]]

[wrap xs] wraps the entire result of wrap xs . [wrap xs]包裹的整个结果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. 您只需要包装列表其余部分的每个元素,而这正是wrap xs已经完成的工作。 Thus, wrap is: 因此, wrap

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 . 错误告诉您正在尝试使用[t] ,GHC期望t This is exactly what we said above, that you are wrapping something too many times. 这正是我们上面所说的,您正在包装很多东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM