nodakai
nodakai

Reputation: 8033

F#: if-else as an expression (returning values)?

Suppose I'm trying to write a clone of the xxd command in F#. It has two operation modes; one to convert a binary file into a hex dump, and another (selected by -r) to convert the hex dump back into a binary file.

Some languages allow me to write something like this:

let (inputFile, isReverse) = if args.[0] == "-r" then
    (args.[1], true)
else
    (args.[0], false)
...
if false == isReverse then
    forwardMode inputFile
else
    reverseMode inputFile

But this doesn't seem to compile under F#. Are there any idiomatic ways to write this in F#? I'm not a great fan of ref or mutable, though I know I would be able to write something like this with them:

let isReverse = ref false
let fileName = ref args.[0]
if !args.[0] == "-r" then
    isReverse := true
    fileName := args.[1]
...
if false == !isReverse then
    forwardMode !inputFile
else
    reverseMode !inputFile

Note: I'm not interested in nice command line parser libraries which I might or might not get with nuget.

Upvotes: 0

Views: 152

Answers (1)

John Palmer
John Palmer

Reputation: 25516

This should be fine F#

let (inputFile, isReverse) = 
    if args.[0] = "-r" then
        (args.[1], true)
    else
        (args.[0], false)
...
if false = isReverse then
    forwardMode inputFile
else
    reverseMode inputFile

Two changes: indent the if and replace == with =

Upvotes: 3

Related Questions