开发者

infinite sequence in SML

I have to code a function that receives a sequence (finite or infinite) and returns an identical sequence with the only difference that if an exception occurs during the sequence then the function returns the sequence to its beginning.

In other words, the function must return a cyclic sequence which repeated itself when it comes to an end. I have to catch the exception with handle.

The following example must work.

  • listToSeq [1,2];

    val it = Cons (1,fn) : int seq

  • restartOnError it;

    val it = Cons (1,fn) : int seq

  • tail it;

    val it = Cons (2,开发者_运维技巧fn) : int seq

  • tail it;

    val it = Cons (1,fn) : int seq

  • tail it;

    val it = Cons (2,fn) : int seq

Can someone help me ?


Simple. You have a load of Cons(int, ->Cons(int, ...)) things (it looks like), and you want to recurse down. Watch and learn, and think it through. When you call the fn which makes the next elt in the list, you don't want to call it straight, but to handle each time, and go back to the start if you have to. So, you write that fn first. Then, you want a chap that will will tranform any elt into the one in the new list, with the tweaked next fun that sends you back to start. So, you write that guy next (third line below). Finally, just return the answer. Simple, code should be easy to follow (pseudo-code; won't quite compile and may have haskelisms).

fun cycle l =
    let fun handleNext next = ((next()) handle whatever => l);
        fun next (Cons(n, fn)) = Cons(n, fun ()=>next(handleNext fn))
    in next l end;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜