Saturday, April 28, 2012

Quick way to convert a space delimited list to a literal F# data structure

Today, while working on this Unquote issue, I needed to create a literal set of reserved words from a space delimited list found in the F# 2.0 specification. Thanks to the F# interactive and it’s printer, I didn’t need to manually create the literal set by laboriously inserting quotations around each word.

First, I copied and pasted the list of words from the specification into a .fs file and easily made it into a literal multi-line string. Taking care to add an extra space at the end of each line so that the last and first words of two consecutive lines didn’t run together when ultimately split.
let reservedWords = "\
    atomic break checked component const constraint constructor \
    continue eager fixed fori functor include \
    measure method mixin object parallel params process protected pure \
    recursive sealed tailcall trait virtual volatile"

I submitted that to FSI.
val reservedWords : string =
  "atomic break checked component const constraint constructor c"+[156 chars]

Then, in FSI, I set the fsi.PrintLength to 1000 so that I could see the complete list in the output and split by ‘ ‘ and converted to a set.
>  fsi.PrintLength <- 1000;;
val it : unit = ()

> reservedWords.Split(' ') |> set;;
val it : Set<string> =
    ["atomic"; "break"; "checked"; "component"; "const"; "constraint";
     "constructor"; "continue"; "eager"; "fixed"; "fori"; "functor"; "include";
     "measure"; "method"; "mixin"; "object"; "parallel"; "params"; "process";
     "protected"; "pure"; "recursive"; "sealed"; "tailcall"; "trait";
     "virtual"; "volatile"]
You can see that the resulting FSI output is directly usable F# code completing my task.

No comments:

Post a Comment