0
\$\begingroup\$

This is my first F# program.

It's a command line utility that takes a parameter containing a path to an height map bitmap and prints out this height map converted to JSON format.

open System.Drawing

let convertLine (y:int) (bitmap:System.Drawing.Bitmap) =
    [ for x in 0 .. bitmap.Width - 1 -> "\"" + bitmap.GetPixel(x, y).R.ToString() + "\"" ] |> String.concat ", "

let convert (path:string) : string = 
    let bitmap = new System.Drawing.Bitmap(path)
    let results = [ for y in 0 .. bitmap.Height - 1 -> convertLine y bitmap ] |> String.concat ", "

    "{\"X\": \"" + bitmap.Width.ToString() + 
    "\", \"Y\": \"" + bitmap.Width.ToString() + 
    "\", \"values\":[" + results + "]}"

[<EntryPoint>]
let main argv = 
    let arglist = argv |> List.ofSeq

    let returnValue = 
        match arglist with
            | path :: _ -> convert path
            | _ -> "Wrong number of arguments supplied"

    printfn "%s" returnValue

    match returnValue with
        | "Wrong number of arguments supplied" -> 1
        | _ -> 0

I want to make sure to write idiomatic F# and to write in a functional style.

\$\endgroup\$
1
\$\begingroup\$

So I would make some changes:

let returnValue = 
    match arglist with
        | path :: _ -> convert path
        | _ -> "Wrong number of arguments supplied"

should probably be something like

let returnValue = 
    match arglist with
        | path :: _ -> convert path
        | _ ->failwith "Wrong number of arguments supplied"

which would simplify some logic

I would also change the printing to use sprintf

"{\"X\": \"" + bitmap.Width.ToString() + 
"\", \"Y\": \"" + bitmap.Width.ToString() + 
"\", \"values\":[" + results + "]}"

becomes

sprintf "{\"X\": \"%i\", \"Y\": \"%i\", \"values\":[%s]}" (bitmap.Width.ToString() ) (bitmap.Width.ToString() ) results
\$\endgroup\$
  • \$\begingroup\$ Will failtwith return an error (>0) from the command line? \$\endgroup\$ – Gilles Feb 26 '16 at 2:11
  • \$\begingroup\$ Probably - if you want to be paranoid you can use a try catch which is still much nicer that your initial approach \$\endgroup\$ – John Palmer Feb 26 '16 at 2:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.