首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >标准ML :如何在列表中循环?

标准ML :如何在列表中循环?
EN

Stack Overflow用户
提问于 2020-03-27 06:20:56
回答 1查看 84关注 0票数 1

我正在尝试编写一个循环遍历列表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);

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

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

代码语言:javascript
复制
fun cycle n i = 
if i = 0 then n
else cycle (tl n) (i-1) @ [hd(n)];
EN

回答 1

Stack Overflow用户

发布于 2020-03-27 23:57:58

使用if-then-else可以做到这一点:

代码语言:javascript
复制
fun cycle xs n =
    if n = 0
    then []
    else xs @ cycle xs (n - 1)

您可能希望使用模式匹配:

代码语言:javascript
复制
fun cycle xs 0 = []
  | cycle xs n = xs @ cycle xs (n - 1)

但我认为,最优雅的解决方案是使用高阶函数:

代码语言:javascript
复制
fun cycle xs n =
    List.concat (List.tabulate (n, fn _ => xs))

一个稍微困难的任务是如何为惰性列表编写一个无限循环的cycle……

代码语言:javascript
复制
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]在哪里。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60877078

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档