Sml 翻转列表中的替换元素
我已经编写了一个函数,它将翻转列表中的备用元素,但是我必须调用它,然后调用它的方法(我是ML新手,所以如果我使用了错误的术语,我很抱歉)。我宁愿只调用函数,而不必调用函数中的方法。这就是我现在要做的:Sml 翻转列表中的替换元素,sml,smlnj,ml,Sml,Smlnj,Ml,我已经编写了一个函数,它将翻转列表中的备用元素,但是我必须调用它,然后调用它的方法(我是ML新手,所以如果我使用了错误的术语,我很抱歉)。我宁愿只调用函数,而不必调用函数中的方法。这就是我现在要做的: (*3. Flip alternate elements in a list, if n = odd, element n remains at end*) fun flip nil x = x | flip x nil = x | flip (x::xs) (y::ys) = x::y:
(*3. Flip alternate elements in a list, if n = odd, element n remains at end*)
fun flip nil x = x
| flip x nil = x
| flip (x::xs) (y::ys) = x::y::flip xs ys;
fun take l =
if l = nil then nil
else hd l::skip (tl l)
and skip l =
if l = nil then nil
else take (tl l);
但当我称之为反转元素时,我必须称之为:
flip (skip d) (take d);
flip (skip e) (take e);
有没有办法将函数调用为:
flip (d);
如果我调用flip(d)代码>现在,它只是打印
val take = fn : ''a list -> ''a list
val skip = fn : ''a list -> ''a list
提前谢谢大家
编辑:我应该提到d只是一个INT列表:
val d = [1,2,3,4];
假设“翻转列表中的备用元素”意味着将[1,2,3,4,5,6]
转换为[2,1,4,3,6,5]
,如果长度为奇数,则丢弃最后一个元素,那么只需在单个函数中进行模式匹配即可实现:
fun flip (x::y::xs) = y::x::flip xs
| flip _ = []
关于您的代码片段的一些反馈:
- 你的许多括号是不必要的
- 不要使用
hd
/tl
,而是使用模式匹配
- 实际翻转发生在
take
和skip
中
您的flip
可以适当地称为merge
- 如果是这种情况,为了修复
翻转
,只需要一个参数:
fun flip xs = merge (skip xs) (take xs)
使助手函数具有更多参数并调用这些参数是非常有用的
谢谢,这正是我想要的!