views:

128

answers:

1

I am new to F# and I have this code:

if s.Contains("-") then
    let x,y =
      match s.Split [|'-'|] with
      | [|a;b|] -> int a, int b
      | _ -> 0,0

Notice that we validate that there is a '-' in the string before we split the string, so the match is really unnecessary. Can I rewrite this with Options?

I changed this code, it was originally this (but I was getting a warning):

if s.Contains("-") then
    let [|a;b|] = s.Split [|'-'|] 
    let x,y = int a, int b

NOTE: I am splitting a range of numbers (range is expressed in a string) and then creating the integer values that represent the range's minimum and maximum.

+4  A: 

The match is not unnecessary, the string might be "1-2-3" and you'll get a three-element array.

Quit trying to get rid of the match, it is your friend, not your enemy. :) Your enemy is the mistaken attempt at pre-validation (the "if contains" logic, which was wrong).

I think you may enjoy this two-part blog series.

http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!180.entry

http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!181.entry

EDIT

Regarding Some/None comment, yes, you can do

let parseRange (s:string) =
    match s.Split [|'-'|] with 
    | [|a;b|] -> Some(int a, int b)
    | _ -> None

let Example s =
    match parseRange s with
    | Some(lo,hi) -> printfn "%d - %d" lo hi
    | None -> printfn "range was bad"

Example "1-2"
Example "1-2-3"
Example "1"

where parseRange return value is a Some (success) or None (failure) and rest of program can make a decision later based on that.

Brian
good call, thanks :)
Phobis
I just don't want to return 0,0 but I want returning code to deal with a failure, if there is one. I don't know how to use Some/None... is this a place I can use it? I would like to tell the caller that it either succeeded with Some values, or it didn't succeed.
Phobis
using your Some/None example, could I do this? let x,y = Example "1-2" ? How do I use the Some/None value?
Phobis
I read your articles. They were great! Thank you.
Phobis