Sml 标准ML:如何循环浏览列表?
我正试图写一个程序,在一个列表中循环n次。 假设L=[a1,a2,…,an] 我试图实现的是[ai+1,ai+2,…,an,a1,a2,…,ai] 我参考了之前关于这个问题的帖子。但是,我不确定如何获得输出或[ai+1,ai+2,…,an,a1,a2,…,ai] 对于输出:我尝试了 -循环([1,2,3,4],5) 但是,我得到的错误是操作数和运算符不匹配 这是我在上一篇文章中找到的代码:Sml 标准ML:如何循环浏览列表?,sml,smlnj,Sml,Smlnj,我正试图写一个程序,在一个列表中循环n次。 假设L=[a1,a2,…,an] 我试图实现的是[ai+1,ai+2,…,an,a1,a2,…,ai] 我参考了之前关于这个问题的帖子。但是,我不确定如何获得输出或[ai+1,ai+2,…,an,a1,a2,…,ai] 对于输出:我尝试了 -循环([1,2,3,4],5) 但是,我得到的错误是操作数和运算符不匹配 这是我在上一篇文章中找到的代码: fun cycle n i = if i = 0 then n else cycle (tl n) (i
fun cycle n i =
if i = 0 then n
else cycle (tl n) (i-1) @ [hd(n)];
使用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))
一个稍微困难的任务是如何为无限循环的惰性列表编写
循环
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 = ...
其中
取5(循环(从列表[1,2])=[1,2,1,2,1]
使用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))
一个稍微困难的任务是如何为无限循环的惰性列表编写
循环
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]
您的函数是curry,因此您希望将其称为cycle[1,2,3,4]5
而不是cycle([1,2,3,4],5)
(尽管您可能会注意到错误!)。谢谢!是的,我得到了错误“uncaughtexceptionempty”。我会看看我是否能解决这个问题。你可能会发现文档也很有用。你的函数是curry函数,所以你想把它称为cycle[1,2,3,4]5
,而不是cycle([1,2,3,4],5)
(尽管你这样做的时候可能会注意到错误!)。谢谢!是的,我得到了错误“uncaughtexceptionempty”。我会看看我是否能解决这个问题。你可能会发现文档也很有用。