【问题标题】:How to change item in a list with sml?如何使用 sml 更改列表中的项目?
【发布时间】:2015-01-31 23:08:07
【问题描述】:

我有一个元组列表,我想要一个函数在这个列表中随机选择两个元组,然后交换这两个元组。

例如,如果我有一个列表为 ((0 , 0), (1 , 0), (1 , 1), (1 , 2) ,(2 , 2), (0 , 2)),然后,随机选择两个元组。如果选择 (0,0) 和 (1,0),则此函数的返回结果将为 ((1 , 0), (0 , 0), (1 , 1), (1 , 2) ,( 2 , 2), (0 , 2))。

我是 SML 的新手,我在其中苦苦挣扎。有一个伪代码,我想它是不正确的,任何人都可以帮助我正确的吗? :

  fun permutation(lst:(int*int) list)=
  let
    val nextInt = Random.randRange (1,List.length(lst))
    val r = Random.rand (1,1)
    val x1 = nextInt r
    val x2 = nextInt r
    val temp = sub(lst,r1)
    update(lst,r1,sub(lst,r2))
    update(lst,r2,temp)
  in
    lst
  end

【问题讨论】:

    标签: sml ml


    【解决方案1】:

    您可以做一个简单的事情,即创建一个辅助函数,该函数接受两个索引和一个列表,并返回这些索引处的两个元组。类似的东西

    fun get_two (i1, i2, xs) =
      let
        fun aux (_, _, [], _, val1, val2) = (val1, val2)
          | aux (i1, i2, x::xs, current_index, val1, val2) =
              if i1 = current_index
              then aux (i1, i2, xs, current_index + 1, SOME x, val2)
              else if i2 = current_index
              then aux (i1, i2, xs, current_index + 1, val1, SOME x)
              else aux (i1, i2, xs, current_index + 1, val1, val2)
      in
        aux (i1, i2, xs, 0, NONE, NONE)
      end
    

    然后编写另一个接收列表的函数,使用此 get_two 辅助函数查找两个值及其在列表中的位置,并生成一个与输入列表相同的新列表,除了这两个值交换了。

    【讨论】:

      猜你喜欢
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      • 2017-09-27
      • 2022-01-14
      相关资源
      最近更新 更多