SML是否与Python的范围()类似?

时间:2012-02-22 15:58:59

标签: python range sml

我正在寻找一个带有非负整数的SML函数,并返回从0开始但不包括给定值的所有整数的列表,类似于Python中的range()。是的,我可以(并且已经)编写自己的内容,但我更喜欢内置的内容,我不需要复制并粘贴到我想要使用它的每个项目中。任何想法?提前谢谢!

% Python code
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

(* SML code: my implementation; I'd prefer a built-in version *)
fun range x = 
    let fun helper current stop = 
        if current = stop 
        then nil 
        else current :: (helper (current + 1) stop)
    in helper 0 x
    end;

(* my code when run *)
- range 10;
val it = [0,1,2,3,4,5,6,7,8,9] : int list

2 个答案:

答案 0 :(得分:14)

这可能不那么可读,但是......

- List.tabulate(10, fn x => x)
val it = [0,1,2,3,4,5,6,7,8,9] : int list

答案 1 :(得分:0)

怎么样:

fun ranger 0 = [ 0 ]
  | ranger x = x :: range x-1 

fun range x = reverse (ranger x)