Advertisement
Guest User

Untitled

a guest
Jul 25th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 0.83 KB | None | 0 0
  1.  
  2.  
  3.  
  4. let (|EmptySet|_|) a = if Set.isEmpty a then Some () else None
  5.  
  6. let (|SetHead|_|) set =
  7.     match set |> Set.toList with
  8.     | head::_ -> Some head
  9.     | _ -> None
  10.  
  11. let hasZeroSum set =
  12.     let rec hasZeroSum sum set  =
  13.         match set with
  14.         | EmptySet -> false // Empty set doesn't count
  15.         | SetHead head when (head + sum) = 0 -> // Is first element + current sum = 0? Success!
  16.             true
  17.         | _ ->
  18.             // Try any (element + current sum) with rest of set
  19.             set |> Set.exists (fun i ->
  20.                 set
  21.                 |> Set.remove i
  22.                 |> hasZeroSum (i + sum)
  23.             )
  24.  
  25.     hasZeroSum 0 set
  26.  
  27.  
  28. [<EntryPoint>]
  29. let main argv =
  30.    
  31.     [10; 20; -5; -13; -3; 1; 56]
  32.     |> Set.ofList
  33.     |> hasZeroSum
  34.     |> printfn "Has any zero sums? %A"
  35.  
  36.     0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement