简体   繁体   中英

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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