【问题标题】:Standard ML :How to cycle through a list?标准 ML:如何循环浏览列表?
【发布时间】:2020-07-07 15:58:26
【问题描述】:

我正在尝试编写一个循环遍历列表 n 次的程序。 假设 L = [a1, a2, ... , an] 我想要实现的是 [ai+1, a i+2, ... , an, a1, a2, ... , ai]。

我参考了之前关于这个确切问题的帖子。但是,我不确定如何获得输出或 [ai+1, a i+2, ... , an, a1, a2, ... , ai]。

对于输出:我试过了 -循环([1,2,3,4],5);

但是我得到的错误是操作数和运算符不匹配

这是我从上一篇文章中找到的代码:

fun cycle n i = 
if i = 0 then n
else cycle (tl n) (i-1) @ [hd(n)];

【问题讨论】:

  • 你的函数是柯里化的,所以你需要把它称为cycle [1,2,3,4] 5而不是cycle([1,2,3,4], 5)(虽然你这样做时可能会注意到一个错误!)。
  • 谢谢你!是的,我收到错误“未捕获的异常为空”。我会看看我能不能解决这个问题。
  • 您可能会发现 this 文档也很有帮助。

标签: sml smlnj


【解决方案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))

一个稍微困难的任务是如何为无限循环的惰性列表编写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].

【讨论】:

    猜你喜欢
    • 2017-11-03
    • 2015-04-05
    • 2020-10-14
    • 2016-08-08
    • 2020-01-02
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    相关资源
    最近更新 更多