15

I was trying to use Seq.first today, and the compiler says it has been deprecated in favor of Seq.tryPick. It says that it applies a function and returns the first result that returns Some. I guess I can just say fun x -> x!=0 since I know the first one will return Some in my case, but what is the proper constraint to put here? What is the correct syntax?

To clarify, I want to use it in the format:

let foo(x:seq<int>) =
   x.filter(fun x -> x>0)
   |> Seq.tryPick (??)
esac
  • 24,099
  • 38
  • 122
  • 179

1 Answers1

29

The key is that 'Seq.first' did not return the first element, rather it returned the first element that matched some 'choose' predicate:

let a = [1;2;3]
// two ways to select the first even number (old name, new name)
let r1 = a |> Seq.first (fun x -> if x%2=0 then Some(x) else None) 
let r2 = a |> Seq.tryPick (fun x -> if x%2=0 then Some(x) else None) 

If you just want the first element, use Seq.head

let r3 = a |> Seq.head 
Ryan Lundy
  • 204,559
  • 37
  • 180
  • 211
Brian
  • 117,631
  • 17
  • 236
  • 300
  • Thanks, I just tried 'seq.first' and got the deprecated message, but have never used it before, so I didn't know the exact syntax. Seq.hd works perfect. – esac Sep 27 '09 at 01:14
  • 7
    FYI, this appears to have been changed to `Seq.head` in F# 2.0. – elo80ka May 01 '11 at 00:10