F#递归函数:使列表项唯一 [英] F# Recursive Functions: make list items unique

查看:83
本文介绍了F#递归函数:使列表项唯一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

let rec isolate (l:'a list) = 
    match l with
    | [] -> []
    | x::xs ->
        if memberof(x,xs)
        then remove (x,l)
        else isolate xs

我已经创建了memberof和remove函数,唯一的问题是当执行第6行remove(x,l)时,它不会继续使用isolate(xs)来继续搜索列表.

I've already created functions memberof and remove, the only problem is that when line 6 remove(x,l) executes it doesn't continue with isolate(xs) for continued search through the list.

有没有办法说,

if x then f(x) and f(y)

?

推荐答案

在使用F#不可变列表时,remove的结果需要存储在某个位置:

As you are using F# immutable lists, the result of remove needs to be stored somewhere:

let rec isolate (l:'a list) = 
    match l with
    | [] -> []
    | x::xs ->
        if memberof(x,xs)
        then
            let xs = remove (x,l)
            isolate xs
        else isolate xs

要回答您的一般性问题:

To answer your more general question:

let f _ = ()
let f' z = z

let x = true
let y = 42
let z = 3.141

if x then
    f y
    f' z |> ignore

此处需要ignore,因为在F#中没有语句,只有表达式,因此您可以将if x then f' z视为

The ignore is needed here because in F# there are no statements, just expressions, so you can think of if x then f' z as

if x then
    f' z
else
    ()

,因此第一个分支也需要返回().

and thus the first branch needs to return () as well.

这篇关于F#递归函数:使列表项唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆