我正在尝试编写一个循环遍历列表n次的程序。假设L= a1,a2,...,我要实现的是ai+1,a i+2,...,an,a1,a2,...,ai。
我参考了上一篇关于这个问题的文章。但是,我不确定如何获得输出或ai+1,a i+2,...,an,a1,a2,...,ai。
对于输出:我尝试了-cycle(1,2,3,4,5);
但是,我得到的错误是操作数和运算符不匹配
这是我在上一篇文章中找到的代码:
fun cycle n i =
if i = 0 then n
else cycle (tl n) (i-1) @ [hd(n)];发布于 2020-03-27 23:57:58
使用if-then-else可以做到这一点:
fun cycle xs n =
if n = 0
then []
else xs @ cycle xs (n - 1)您可能希望使用模式匹配:
fun cycle xs 0 = []
| cycle xs n = xs @ cycle xs (n - 1)但我认为,最优雅的解决方案是使用高阶函数:
fun cycle xs n =
List.concat (List.tabulate (n, fn _ => xs))一个稍微困难的任务是如何为惰性列表编写一个无限循环的cycle……
datatype 'a lazylist = Cons of 'a * (unit -> 'a lazylist) | Nil
fun fromList [] = Nil
| fromList (x::xs) = Cons (x, fn () => fromList xs)
fun take 0 _ = []
| take _ Nil = []
| take n (Cons (x, tail)) = x :: take (n - 1) (tail ())
local
fun append' (Nil, ys) = ys
| append' (Cons (x, xtail), ys) =
Cons (x, fn () => append' (xtail (), ys))
in
fun append (xs, Nil) = xs
| append (xs, ys) = append' (xs, ys)
end
fun cycle xs = ...take 5 (cycle (fromList [1,2])) = [1,2,1,2,1]在哪里。
https://stackoverflow.com/questions/60877078
复制相似问题