【发布时间】:2012-03-01 05:30:18
【问题描述】:
我想创建一个类型为int -> 'a list -> 'a list list的函数
函数调用:
grupper 2 [3, 1, 4, 1, 5, 9] 应返回[[3, 1], [4, 1], [5, 9]]
grupper 4 [3, 1, 4, 1, 5, 9] 应返回[[3, 1, 4, 1], [5, 9]]
grupper 42 [3, 1, 4, 1, 5, 9] 应返回[[3, 1, 4, 1, 5, 9]]。
到现在为止
fun grupper _ [] = []
| grupper n (x::xs) = if n > length(x::xs) then [x::xs]
else [List.take(x::xs, n)] @ grupper (n) xs
请帮忙。
【问题讨论】:
-
您应该始终避免使用附加 (@),尤其是当您将第一个元素设为列表只是为了附加它时。在这里(如 pad 所示),您可以使用 cons 运算符 (::) 将元素放入
grupper返回的列表中。
标签: list functional-programming sml