简体   繁体   English

SML中的递归函数

[英]Recursive function in SML

I'm struggling with SML because I need it for my master thesis but I've never used before. 我正在为SML苦苦挣扎,因为我的硕士论文需要它,但是我从未使用过。 I need to define a function which takes as input a list of tuple of kind: (string * string * string) list 我需要定义一个函数,该函数将类型为元组的列表作为输入:(string * string * string)list

and return a list of different tuple of kind: ((string * (string * string * string)) * ((string * string * string) * string)) list 并返回不同类型的元组的列表:((string *(string *字符串*字符串))*((string *字符串*字符串)*字符串))list

The problem is that I'm using the recursive concept to create a dynamic list but I cannot find a way. 问题是我正在使用递归概念来创建动态列表,但找不到方法。 My code so far is: 到目前为止,我的代码是:

fun insertRelationLts ((x,y,z),nil) = 
        let val h=(x,y,z)
        in [((x,h),(h,z))]
        end
| insertRelationLts ((x,y,z),(a,b,c)::(d,e,f)) = 
        let val h=(x,y,z)
            val q=x
            val w=z
        in ((q,h),(h,w))::insertRelationLts((a,b,c),(d,e,f))     
        end

I hope someone can help me. 我希望有一个人可以帮助我。 Thanks a lot! 非常感谢!

The cons operator :: expects a list on the right, but the tuple (d,e,f) isn't one. 缺点运算符::期望在右边有一个列表,但元组(d,e,f)不是一个。 There is no reason to pattern-match it either, so just replace both occurrences of (d,e,f) with a variable and it should type-check. 也没有理由对其进行模式匹配,因此只需将两个出现的(d,e,f)替换为一个变量,然后对其进行类型检查。 You can also simplify a little: 您还可以简化一下:

fun insertRelationLts (h as (x,y,z), nil) = [((x,h),(h,z))]
  | insertRelationLts (h as (x,y,z), t::rest) = 
      ((x,h),(h,z))::insertRelationLts(t, rest)     

I would, however, recommend using records or at least some type abbreviations for more clarity. 但是,我建议使用记录或至少使用某些类型的缩写以更清楚。

Edit: In fact, this function can be expressed even more easily without explicit recursion: 编辑:实际上,无需显式递归就可以更轻松地表达此函数:

fun insertRelationsLts (h, list) =
    map (fn h as (x,y,z) => ((x,h), (h,z))) (h::list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM