Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor code clean-up #566

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/content/samples/presidents.fsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ let presidentTerms =
if string pos.``Basic title`` = "President" then
// Get start and end year of the position
let starty = DateTime.Parse(pos.From).Year
let endy = if pos.To = null then 2013 else
let endy = if isNull pos.To then 2013 else
DateTime.Parse(pos.To).Year
// Get their party
let dem = pres.Party |> Seq.exists (fun p -> p.Party.Name = "Democratic Party")
Expand Down
2 changes: 1 addition & 1 deletion docs/tools/formatters.fsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ open FSharp.Charting.ChartTypes
/// Extract values from any series using reflection
let (|SeriesValues|_|) (value:obj) =
let iser = value.GetType().GetInterface("ISeries`1")
if iser <> null then
if not (isNull iser) then
let keys = value.GetType().GetProperty("Keys").GetValue(value) :?> System.Collections.IEnumerable
let vector = value.GetType().GetProperty("Vector").GetValue(value) :?> IVector
Some(Seq.zip (Seq.cast<obj> keys) vector.ObjectSequence)
Expand Down
30 changes: 15 additions & 15 deletions src/Deedle.Excel/Excel.fs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module Deedle.Excel
module Deedle.Excel

open Deedle

Expand Down Expand Up @@ -87,21 +87,21 @@ let openNewExcelApplication () =
excelApp

let private assertInstance () =
if excelApp <> null then
if not (isNull excelApp) then
let wbs = excelApp.Workbooks
if wbs.Count = 0 then
wbs.Add(Enums.XlWBATemplate.xlWBATWorksheet) |> ignore

if excelApp = null then
if isNull excelApp then
openNewExcelApplication () |> ignore
elif activeWb <> null then
elif not (isNull activeWb) then
activeWb.Activate()

let private openWorkbook (readonly : bool) filename =
excelApp.get_Workbooks().Open(filename, null, readonly)

let getActiveWorkbook () =
if activeWb = null then
if isNull activeWb then
excelApp.ActiveWorkbook
else
activeWb
Expand Down Expand Up @@ -146,7 +146,7 @@ let getRealRange (range : obj) =
assertInstance ()
match range with
| :? string as str ->
let idx = str.IndexOf("!")
let idx = str.IndexOf '!'
if idx > 0 then switchSheet (str.Substring(0, idx))
| _ -> ()
excelApp.Range(range)
Expand All @@ -171,7 +171,7 @@ let private unionRanges r1 r2 =
RealExcel (excelApp.Union(real1, real2))

let private putArray isH (arr : obj [,]) startRange =
if arr = null || Array2D.length1 arr = 0 || Array2D.length2 arr = 0 then
if isNull arr || Array2D.length1 arr = 0 || Array2D.length2 arr = 0 then
startRange
else
let (height, width) = arr |> arraySize
Expand Down Expand Up @@ -330,7 +330,7 @@ module internal XlHelper =
|> aptest showCols (putArray false t.ColumnHeaders)
|> putArray false t.DataArray
|> aptest showRows (moveLeftCols 1 >> skipHistory 1)
|> aptest (tableStyle <> null) (applyToHistory (fun r->
|> aptest (not (isNull tableStyle)) (applyToHistory (fun r->
ExcelStyles.ApplyTableStyle(r,tableStyle, showFilter, showRows)))

// ----------------------------------------------------------------------------------------
Expand Down Expand Up @@ -361,7 +361,7 @@ module internal XlHelper =
| _ -> box ""

let formatExcelHeader (value:obj) =
if value = null then box "" else
if isNull value then box "" else
match formatMap.TryGetValue(value.GetType()) with
| true, f -> f value
| _ -> box (value.ToString())
Expand Down Expand Up @@ -404,7 +404,7 @@ type Xl =
for cf in fs do
for c in cf.Columns do
let colRange = range.Find(c,null,null,Enums.XlLookAt.xlWhole,null)
if colRange <> null then
if not (isNull colRange) then
{state with LastRange = (RealExcel (colRange |> resize(rows,1)))} |> cf.Format |> ignore
state

Expand All @@ -415,7 +415,7 @@ type Xl =
for cf in fs do
for c in cf.Columns do
let colRange = range.Find(c,null,null,Enums.XlLookAt.xlWhole,null)
if colRange <> null then
if not (isNull colRange) then
{state with LastRange = (RealExcel colRange.EntireColumn)} |> cf.Format |> ignore
state

Expand Down Expand Up @@ -447,7 +447,7 @@ type Xl =
let range = (lastRange |> convertRange)
for cd in ds do
let colRange = range.Find(cd.Column,null,null,Enums.XlLookAt.xlWhole,null)
if colRange <> null then
if not (isNull colRange) then
let c = colRange.AddComment(cd.Description)
c.Visible <- false
c.Shape.TextFrame.AutoSize <- true
Expand All @@ -459,7 +459,7 @@ type Xl =
let range = (lastRange |> convertRange)
let startRange = range.Find(cStart,null,null,Enums.XlLookAt.xlWhole,null)
let endRange = range.Find(cEnd,null,null,Enums.XlLookAt.xlWhole,null)
if startRange <> null && endRange <> null then
if not( isNull startRange) && not (isNull endRange) then
let startAddress = startRange.Address
let endAddress = endRange.Address
let r = getRealRange (startAddress + ":" + endAddress)
Expand Down Expand Up @@ -528,7 +528,7 @@ type DynamicExcel(app, ?keepInSync) =
and set (choice) = keepInSync <- choice

member private this.createInstance() =
if localExcelApp = null then
if isNull localExcelApp then
localExcelApp <- openNewExcelApplication()
else
()
Expand Down Expand Up @@ -644,7 +644,7 @@ let GetFsiSeriesAndFrames (knownTypes : ICollection<Type>) =
&& pi.PropertyType <> typeof<Unit>
then
let pv = pi.GetValue(null, Array.empty)
if pv <> null then
if not (isNull pv) then
match pv with
| GenericSeries argTypes | GenericFrame argTypes ->
yield { name = pi.Name; type_ = pi.PropertyType; value = pi.GetValue(null, Array.empty); }
Expand Down
4 changes: 2 additions & 2 deletions src/Deedle/Common/BinomialHeap.fs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/// Purely functional Binomial Heap implementation
/// Purely functional Binomial Heap implementation
/// Based on: http://cs.hubfs.net/topic/None/56608
///
/// Characteristics:
Expand Down Expand Up @@ -40,7 +40,7 @@ module BinomialHeap =
{ Comparer = comparer; Heap = [] }

/// Returns true when the specified heap is emtpy
let isEmpty heap = heap.Heap = []
let isEmpty heap = List.isEmpty heap.Heap

/// Returns the rank of the specified tree node
let internal rank (Node (r,_,_)) = r
Expand Down
6 changes: 3 additions & 3 deletions src/Deedle/Common/Common.fs
Original file line number Diff line number Diff line change
Expand Up @@ -820,7 +820,7 @@ module Seq =
// Walk over all windows; use 'f' to determine if the item
// should be added - if so, add it, otherwise yield window
let win = ref windows.First
while win.Value <> null do
while not (isNull win.Value) do
let start, items = win.Value.Value
let next = win.Value.Next
if f start v then win.Value.Value <- start, v::items
Expand Down Expand Up @@ -1004,7 +1004,7 @@ module Seq =
// Walk over all windows; use 'f' to determine if the item
// should be added - if so, add it, otherwise yield window
let win = ref windows.First
while win.Value <> null do
while not (isNull win.Value) do
let value, startIdx, endIdx = win.Value.Value
let next = win.Value.Next
if f value v then win.Value.Value <- value, startIdx, !index
Expand Down Expand Up @@ -1467,7 +1467,7 @@ module Convert =
else System.Convert.ChangeType(value, typeof<'T>) :?> 'T
| ConversionKind.Safe ->
if value :? 'T then value :?> 'T
elif value <> null then
elif not (isNull value) then
match sourcesByTarget.TryGetValue(typeof<'T>) with
| true, sources when sources.ContainsKey(value.GetType()) ->
System.Convert.ChangeType(value, typeof<'T>) :?> 'T
Expand Down
3 changes: 2 additions & 1 deletion src/Deedle/FSharp.Data/CommonRuntime/IO.fs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/// Helper functions called from the generated code for working with files
/// Helper functions called from the generated code for working with files
module FSharp.Data.Runtime.IO

open System
Expand All @@ -7,6 +7,7 @@ open System.IO
open System.Text
open FSharp.Data

[<Struct>]
type internal UriResolutionType =
| DesignTime
| Runtime
Expand Down
59 changes: 36 additions & 23 deletions src/Deedle/FSharp.Data/CommonRuntime/NameUtils.fs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/// Tools for generating nice member names that follow F# & .NET naming conventions
/// Tools for generating nice member names that follow F# & .NET naming conventions
module FSharp.Data.Runtime.NameUtils

open System
Expand All @@ -9,6 +9,7 @@ open FSharp.Data.Runtime
// --------------------------------------------------------------------------------------
// Active patterns & operators for parsing strings

// Todo: Convert to ValueTuple and [<return: Struct>] when F# 6 is available
let private tryAt (s:string) i = if i >= s.Length then None else Some s.[i]
let private sat f (c:option<char>) = match c with Some c when f c -> Some c | _ -> None
let private (|EOF|_|) c = match c with Some _ -> None | _ -> Some ()
Expand All @@ -18,41 +19,53 @@ let private (|Lower|_|) = sat (fun c -> Char.IsLower c || Char.IsDigit c)

// --------------------------------------------------------------------------------------

let inline internal forall predicate (source : ReadOnlySpan<_>) =
let mutable state = true
let mutable e = source.GetEnumerator()
while state && e.MoveNext() do
state <- predicate e.Current
state

/// Turns a given non-empty string into a nice 'PascalCase' identifier
let nicePascalName (s:string) =
if s.Length = 1 then s.ToUpperInvariant() else
// Starting to parse a new segment
let rec restart i = seq {
let rec restart i =
match tryAt s i with
| EOF -> ()
| LetterDigit _ & Upper _ -> yield! upperStart i (i + 1)
| LetterDigit _ -> yield! consume i false (i + 1)
| _ -> yield! restart (i + 1) }
| EOF -> Seq.empty
| LetterDigit _ & Upper _ -> upperStart i (i + 1)
| LetterDigit _ -> consume i false (i + 1)
| _ -> restart (i + 1)
// Parsed first upper case letter, continue either all lower or all upper
and upperStart from i = seq {
and upperStart from i =
match tryAt s i with
| Upper _ -> yield! consume from true (i + 1)
| Lower _ -> yield! consume from false (i + 1)
| Upper _ -> consume from true (i + 1)
| Lower _ -> consume from false (i + 1)
| _ ->
yield from, i
yield! restart (i + 1) }
seq {
yield struct (from, i)
yield! restart (i + 1)
}
// Consume are letters of the same kind (either all lower or all upper)
and consume from takeUpper i = seq {
match tryAt s i with
| Lower _ when not takeUpper -> yield! consume from takeUpper (i + 1)
| Upper _ when takeUpper -> yield! consume from takeUpper (i + 1)
| Lower _ when takeUpper ->
yield from, (i - 1)
yield! restart (i - 1)
and consume from takeUpper i =
match takeUpper, tryAt s i with
| false, Lower _ -> consume from takeUpper (i + 1)
| true, Upper _ -> consume from takeUpper (i + 1)
| true, Lower _ ->
seq {
yield struct (from, (i - 1))
yield! restart (i - 1)
}
| _ ->
yield from, i
yield! restart i }
seq {
yield struct(from, i)
yield! restart i }

// Split string into segments and turn them to PascalCase
seq { for i1, i2 in restart 0 do
let sub = s.Substring(i1, i2 - i1)
if Array.forall Char.IsLetterOrDigit (sub.ToCharArray()) then
yield sub.[0].ToString().ToUpperInvariant() + sub.ToLowerInvariant().Substring(1) }
let sub = s.AsSpan(i1, i2 - i1)
if forall Char.IsLetterOrDigit sub then
yield Char.ToUpperInvariant(sub.[0]).ToString() + sub.Slice(1).ToString().ToLowerInvariant() }
|> String.Concat

/// Turns a given non-empty string into a nice 'camelCase' identifier
Expand Down
4 changes: 2 additions & 2 deletions src/Deedle/FSharp.Data/CommonRuntime/StructuralInference.fs
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ let parseUnitOfMeasure (provider:IUnitsOfMeasureProvider) (str:string) =
if str.EndsWith suffix then
let baseUnitStr = str.[..str.Length - suffix.Length - 1]
let baseUnit = provider.SI baseUnitStr
if baseUnit = null then
if isNull baseUnit then
None
else
baseUnit |> trans provider |> Some
Expand All @@ -313,4 +313,4 @@ let parseUnitOfMeasure (provider:IUnitsOfMeasureProvider) (str:string) =
| Some _ -> unit
| None ->
let unit = provider.SI str
if unit = null then None else Some unit
if isNull unit then None else Some unit
4 changes: 2 additions & 2 deletions src/Deedle/FSharp.Data/CommonRuntime/TextRuntime.fs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace FSharp.Data.Runtime
namespace FSharp.Data.Runtime

open System
open System.Globalization
Expand All @@ -19,7 +19,7 @@ type TextRuntime =
then CultureInfo.InvariantCulture
else
let mutable cache = TextRuntime.cultureInfoCache
if cache = null then
if isNull cache then
cache <- Collections.Generic.Dictionary<string, CultureInfo> ()
TextRuntime.cultureInfoCache <- cache
match cache.TryGetValue cultureStr with
Expand Down
12 changes: 6 additions & 6 deletions src/Deedle/FSharp.Data/Net/Http.fs
Original file line number Diff line number Diff line change
Expand Up @@ -1199,7 +1199,7 @@ module private HttpHelpers =
source.Dispose ()
}

let runningOnMono = try System.Type.GetType("Mono.Runtime") <> null with e -> false
let runningOnMono = try not(isNull (System.Type.GetType "Mono.Runtime")) with e -> false

let writeBody (req:HttpWebRequest) (data: Stream) =
async {
Expand All @@ -1212,7 +1212,7 @@ module private HttpHelpers =
let reraisePreserveStackTrace (e:Exception) =
try
let remoteStackTraceString = typeof<exn>.GetField("_remoteStackTraceString", BindingFlags.Instance ||| BindingFlags.NonPublic);
if remoteStackTraceString <> null then
if not (isNull remoteStackTraceString) then
remoteStackTraceString.SetValue(e, e.StackTrace + Environment.NewLine)
with _ -> ()
raise e
Expand All @@ -1223,7 +1223,7 @@ module private HttpHelpers =
with
// If an exception happens, augment the message with the response
| :? WebException as exn ->
if exn.Response = null then reraisePreserveStackTrace exn
if isNull exn.Response then reraisePreserveStackTrace exn
let responseExn =
try
let newResponse = new WebResponse(exn.Response)
Expand Down Expand Up @@ -1332,7 +1332,7 @@ module private HttpHelpers =
return! getResponseAsync req
with
| :? WebException as exc ->
if exc.Response <> null then
if not (isNull exc.Response) then
return exc.Response
else
reraisePreserveStackTrace exc
Expand Down Expand Up @@ -1601,14 +1601,14 @@ type Http private() =
let cookies = CookieHandling.getCookiesAndManageCookieContainer uri resp.ResponseUri headers cookieContainer
addCookiesFromHeadersToCookieContainer (defaultArg silentCookieErrors false)

let contentType = if resp.ContentType = null then "application/octet-stream" else resp.ContentType
let contentType = if isNull resp.ContentType then "application/octet-stream" else resp.ContentType

let statusCode, characterSet =
match resp with
| :? HttpWebResponse as resp -> int resp.StatusCode, resp.CharacterSet
| _ -> 0, ""

let characterSet = if characterSet = null then "" else characterSet
let characterSet = if isNull characterSet then "" else characterSet

let stream = resp.GetResponseStream()

Expand Down
3 changes: 1 addition & 2 deletions src/Deedle/Frame.fs
Original file line number Diff line number Diff line change
Expand Up @@ -1662,8 +1662,7 @@ and Frame<'TRowKey, 'TColumnKey when 'TRowKey : equality and 'TColumnKey : equal
|> Seq.zip offsets // seq of (srcloc, label)
|> Seq.zip frame.RowKeys // seq of (rowkey, (srcloc, label))
|> Seq.groupBy (fun (rk, (i, l)) -> l) // seq of (label, seq of (rowkey, (srcloc, label)))
|> Seq.map (fun (k, s) -> s) // seq of (seq of (rowkey, (srcloc, label)))
|> Seq.concat // seq of (rowkey, (srcloc, label))
|> Seq.collect (fun (k, s) -> s) // seq of (rowkey, (srcloc, label))
|> Seq.zip offsets // seq of (dstloc, (rowkey, (srcloc, label)))
|> Seq.map (fun (dst, (rowkey, (src, grp))) ->
(grp, rowkey), (dst, src)) // seq of (label, rowkey), (dstloc, srcloc)
Expand Down
Loading
Loading