F#查找另一个数组中的所有元素

时间:2016-10-04 22:37:00

标签: f#

此解决方案

d1 |> Array.filter (fun t -> d2 |> Array.exists (fun t2 -> t=t2))

从这个回答

Finding the difference between two arrays in FSharp

发出此错误

Severity    Code    Description Project File    Line    Suppression State
Error       Type mismatch. Expecting a
    unit -> bool    
but given a
    'a [] -> bool    
The type 'unit' does not match the type ''a []' ParseLibs   
Program.fs  25  

完整代码:

// Learn more about F# at http://fsharp.org
// See the 'F# Tutorial' project for more help.

open System
open System.IO

open FSharp.Collections

[<EntryPoint>]
let main argv = 
    let path = "data1.txt"
    let lines = use reader = new StreamReader(path) in reader.ReadToEnd().Split('\n')
    let n = 5

    let d1 = lines 
            |> Array.takeWhile (fun e -> not (e.Equals "\r")) 

    let d2 = lines 
            |> Array.skipWhile (fun e -> not (e.Equals "\r")) 
            |> Array.skip 1
            |> Array.mapi (fun i e -> e, i)
            |> Array.filter (fun (e, i) -> i % n = 0)
            |> Array.iter (fun (e, i) -> printfn "%s" e)

    d1 |> Array.filter (fun t -> d2 |> Array.exists (fun t2 -> t=t2))

    //let writer = new StreamWriter(path)

    ignore (Console.ReadKey())
    0 // return an integer exit code

答案有错吗?真正的答案是什么?我只是想过滤两个数组中的所有元素。在大多数函数式语言中,这都是微不足道的。

d1 |> Array.filter (fun t -> d2.contains(t))

2 个答案:

答案 0 :(得分:4)

问题是d2具有类型单位。

array.iter返回()

我会改为

let d2 = lines 
        |> Array.skipWhile (fun e -> not (e.Equals "\r")) 
        |> Array.skip 1
        |> Array.mapi (fun i e -> e, i)
        |> Array.filter (fun (e, i) -> i % n = 0)

d1 
|> Array.filter (fun t -> d2 |> Array.exists (fun t2 -> t=t2)) 
|> Array.iter (fun (e, i) -> printfn "%s" e)

答案 1 :(得分:0)

使用上述链接中的实际答案:https://stackoverflow.com/a/28682277/5514938并在https://en.wikipedia.org/wiki/Set_theory#Basic_concepts_and_notation添加信息 以下代码是具有与wiki文章中相同的集合/值的三个第一个概念的示例。

let d1= [|"1";"2";"3";|] //pretend this to be the filtered/skipped/mapped
                         //whatever but otherwise "clean" structure/datatypes
let d2 = [|"2";"3";"4";|] //pretend this to be the filtered/skipped/mapped
                          //whatever  but otherwise "clean" structure/datatypes 
                          //equal to d1


let s1 = d1 
        |> Set.ofArray

let s2 = d2 
        |> Set.ofArray


let all = s1 + s2 //Union
let inBoth = Set.intersect s1 s2 //Intersection

let onlyIn_d1 = s1 - s2 //Set difference
let onlyIn_d2 = s2 - s1 //Set difference the other way ;-)

我已经删除了您的其他代码以简化概念,因此您正在执行的初始过滤器,跳过和映射当然必须在上述代码之前完成。你还必须&#34;重新调整&#34;类型再次相等:

|> Array.mapi (fun i e -> e, i)
|> Array.filter (fun (e, i) -> i % n = 0)
|> Array.map (fun (e,i) -> e)
|> Set.ofArray