HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Is there any way to improve (shorten) this F# code?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisanywayshortenimprovecodethere

Problem

I have a very good grasp of the syntax and features of F# as well as some of the concepts that mesh well with the language. However, I do not have enough experience writing it to feel comfortable that the way I am handling the language is appropriate.

Ignoring the fact that I do not provide proper escaping functionality for the file format, is there any way I could write this code better? I know that this is a trivial example, but I fear that I might be making things too hard on myself with this code.

Also, is there a way that I could write this more robustly so that adding in an escape sequence for the ";" character would be easier?

module Comments

open System.IO

type Comment = { Author: string; Body: string }

let parseComment (line:string) =
    match line.Split(';') with
    | [|author; body|] -> Some({Author=author; Body=body})
    | _                -> None

let filterOutNone maybe = match maybe with | Some(_) -> true | _ -> false
let makeSome some = match some with | Some(v) -> v | _ -> failwith "error"

let readAllComments () = 
    File.ReadAllLines("comments.txt")
    |> Array.map parseComment
    |> Array.filter filterOutNone
    |> Array.map makeSome

Solution

Most of your code can be replaced with a comprehension:

type Comment = { Author: string; Body: string }

let readAllComments () = 
  [|for line in System.IO.File.ReadAllLines("comments.txt") do
      match line.Split ';' with
      | [|author; body|] -> yield {Author=author; Body=body}
      | _ -> ()|]

Code Snippets

type Comment = { Author: string; Body: string }

let readAllComments () = 
  [|for line in System.IO.File.ReadAllLines("comments.txt") do
      match line.Split ';' with
      | [|author; body|] -> yield {Author=author; Body=body}
      | _ -> ()|]

Context

StackExchange Code Review Q#2665, answer score: 7

Revisions (0)

No revisions yet.