Can I get a list of the values that are not functions in all of the program modules? - module

My F# program runs well but sometimes I find it difficult to understand the flow. I define values that are not functions in many modules. When these modules are opened these values are bound. I would like to obtain a list of all the names of non-function values and in which modules they were declared. Is this possible?
The example below may clarify the question.
module A =
let i = 1
let add x y = x + y
module B =
let x = 99.9
let sqr z = z * z
open A
open B
let y =
add (float i) x
|> sqr
printfn "%f" y
Is there a function foo that would do the following?
let nonFuncVals = foo()
printfn "%A" nonFuncVals
// ["A.i", "B.x"]

There is no built-in support for this. Depending on how you work, you might be able to do this in some hacky way, but it is probably going to have quite a few limitations.
The following works on your example, when you run it using F# interactive, but I'm sure there are many ways in which it can break:
open System.Reflection
let nonFuncVals () =
let special = set [ "it"; "CheckClose"; "LastGenerated" ]
[ for t in Assembly.GetExecutingAssembly().GetTypes() do
if t.FullName.StartsWith "FSI_" then
for p in t.GetProperties() do
if not (special.Contains p.Name) then
if t.FullName.Length <= 8 then yield p.Name
else yield t.FullName.Substring(9) + "." + p.Name ]
|> Seq.distinct
nonFuncVals()
The function looks at the currently defined types and uses the fact that F# Interactive puts generated bindings in types with names such as FSI_0001. This is, however, undocumented behaviour and it can change in the next version...

Related

Why does guard need the Ord typeclass in Idris?

In another question (How to write a simple list-based quicksort in Idris?), I was left trying to understand why Prelude.Applicative.guard requires an Ord typeclass.
Guard is defined like this:
guard : Alternative f => Bool -> f ()
guard a = if a then pure () else empty
Looking at the Alternative interface docs (I don't actually understand how it is defined in the code yet, but I'm not very far along in learning Idris), I don't see how it requires Ord either.
guard alone does not need the Ord constraint, but rather (<) in your previous question. I gave there an answer to distingush between List (Ord b) and Ord b => List b.
To see why guard complains about the missing constraint, see how monad comprehensions are de-sugared.
[y | y <- xs, y < x] becomes do {y <- xs; guard (y < x); pure y}.

Should I leave non-function values in modules or bring them to the main program file?

This is a question about how I should organize my F# code. I hope it is not in violation of SO rules.
I have dozens of source files (names terminating in .fs) in my project. Each file contains a module. In some of these files/modules I define only functions. In others I define functions and other values (not functions).
The last file in the Solution Explorer (Visual Studio) is Program.fs which actually contains very little code. Most calculations have been done "above" it.
I am considering moving the non-function values declared in the other modules to Program.fs. These are the advantages and disadvantages I see from this change:
Advantages:
1) A better view of program flow.
2) Easier to select all code above a certain line and send it for execution in FSI.
3) Slightly easier to search for those values in the editor.
4) Possibly easier to debug by putting breakpoints on the lines where values are declared.
Disadvantages:
1) Program.fs could become large and unwieldy.
2) Loss of modularity.
3) After implementing the changes, if the calculation of value y in module B depends on value x in module A "above" it then I can no longer have y as a value, it must be declared as a function of x. Similarly if a function declaration in module B depends on a value in module A I must add a parameter to the function definition.
Below are two examples of the same small program created under the two alternative methods. Which of the two is better in general?
// ///////////////// Values in modules \\\\\\\\\\\\\\\\\\\\
// File A.fs
module A
let i = 1
let add x y : float = x + y
// File B.fs
module B
let sqr z = z * z + float i
let x = sqr 99.9
// File Program.fs
open A
open B
let y =
add (float i) x
|> sqr
printfn "%f" y
[<EntryPoint>]
let main argv =
printfn "%A" argv
0 // return an integer exit code
// This is the calculated value for y: 99640524.640100
// ///////////////// Values in Program.fs \\\\\\\\\\\\\\\\\\\\
// File A.fs
module A
let add x y : float = x + y
// File B.fs
module B
open A
let sqr i z = z * z + float i // notice the additional parameter
//File Program.fs
open A
open B
let i = 1
let x = sqr i 99.9
let y =
add (float i) x
|> sqr i
printfn "%f" y
[<EntryPoint>]
let main argv =
printfn "%A" argv
0 // return an integer exit code
// This is the calculated value for y: 99640524.640100
As you presented it, the second version (with values moved to Main) is better imho. You pretty much nailed it with the #1 advantage and it's a really big one. As for the disadvantages you listed:
Large main: Yeah, depends on how much stuff we're talking, worst case you could keep the values in yet another module used just by main and just for values. Think "Config module"
Loss of modularity: I can't see
why. If anything it increases the modularity? Your main does not
depend on module X having some value, it provides it. You can then swap the module with another satisfying the same interface and not care about ripple effect it could have on other modules. If you have a large hierarchy of modules you could look into representing it in your main as per dependency inversion principle - it would take some work but the good news is that in functional languages you don't need IoC containers, partial application does the job
If module B depends on a value existing in module A it isn't very modular to begin with, is it? It's a good thing that you will have to change it into a function - it will explicitly say what is now implicit
Note that I'm writing this from my mostly OOP experience, so in functional programming some of it may be not applicable

Idiomatic way of listing elements of a sum type in Idris

I have a sum type representing arithmetic operators:
data Operator = Add | Substract | Multiply | Divide
and I'm trying to write a parser for it. For that, I would need an exhaustive list of all the operators.
In Haskell I would use deriving (Enum, Bounded) like suggested in the following StackOverflow question: Getting a list of all possible data type values in Haskell
Unfortunately, there doesn't seem to be such a mechanism in Idris as suggested by Issue #19. There is some ongoing work by David Christiansen on the question so hopefully the situation will improve in the future : david-christiansen/derive-all-the-instances
Coming from Scala, I am used to listing the elements manually, so I pretty naturally came up with the following:
Operators : Vect 4 Operator
Operators = [Add, Substract, Multiply, Divide]
To make sure that Operators contains all the elements, I added the following proof:
total
opInOps : Elem op Operators
opInOps {op = Add} = Here
opInOps {op = Substract} = There Here
opInOps {op = Multiply} = There (There Here)
opInOps {op = Divide} = There (There (There Here))
so that if I add an element to Operator without adding it to Operators, the totality checker complains:
Parsers.opInOps is not total as there are missing cases
It does the job but it is a lot of boilerplate.
Did I miss something? Is there a better way of doing it?
There is an option of using such feature of the language as elaborator reflection to get the list of all constructors.
Here is a pretty dumb approach to solving this particular problem (I'm posting this because the documentation at the moment is very scarce):
%language ElabReflection
data Operator = Add | Subtract | Multiply | Divide
constrsOfOperator : Elab ()
constrsOfOperator =
do (MkDatatype _ _ _ constrs) <- lookupDatatypeExact `{Operator}
loop $ map fst constrs
where loop : List TTName -> Elab ()
loop [] =
do fill `([] : List Operator); solve
loop (c :: cs) =
do [x, xs] <- apply `(List.(::) : Operator -> List Operator -> List Operator) [False, False]
solve
focus x; fill (Var c); solve
focus xs
loop cs
allOperators : List Operator
allOperators = %runElab constrsOfOperator
A couple comments:
It seems that to solve this problem for any inductive datatype of a similar structure one would need to work through the Elaborator Reflection: Extending Idris in Idris paper.
Maybe the pruviloj library has something that might make solving this problem for a more general case easier.

Preventing FsCheck from generating NaN and infinities

I have a deeply nested datastructure with floats all over the place.
I'm using FsCheck to check if the data is unchanged after serializing and then deserializing.
This property fails, when a float is either NaN or +/- infinity, however, such a case doesn't interest me, since I don't expect these values to occur in the actual data.
Is there a way to prevent FsCheck from generating NaN and infinities?
I have tried discarding generated data that contains said values, but this makes the test incredibly slow, so slow in fact, that the test is still running while I'm writing this, and I have my doubts it will actually finish...
For reflectively generated types that contain floats (as I suspect you're using) you can overwrite the default generator for floats by writing a class as follows:
type Overrides() =
static member Float() =
Arb.Default.Float()
|> filter (fun f -> not <| System.Double.IsNaN(f) &&
not <| System.Double.IsInfinity(f))
And then calling:
Arb.register<Overrides>()
Before FsCheck tries to generate the types; e.g. in your test setup or before calling Check.Quick.
You can check the result of the register method to see how it merged the default arbitrary instances with the new ones; it should have overridden them.
If you are using the xUnit extension you can avoid calling the Arb.register by using the Arbitraries argument of PropertyAttribute:
[<Property(Arbitraries=Overides)>]
As Mauricio Scheffer said, you can use NormalFloat type in test parameter.
Simple example for list of floats:
open FsCheck
let f (x : float list) = x |> List.map id
let propFloat (x : float list) = x = (f x)
let propNormalFloat (xn : NormalFloat list) =
let x = xn |> List.map NormalFloat.get
x = f x
Check.Quick propFloat
//Falsifiable, after 18 tests (13 shrinks) (StdGen (761688149,295892075)):
//[nan]
Check.Quick propNormalFloat
//Ok, passed 100 tests.

Variables in Haskell

Why does the following Haskell script not work as expected?
find :: Eq a => a -> [(a,b)] -> [b]
find k t = [v | (k,v) <- t]
Given find 'b' [('a',1),('b',2),('c',3),('b',4)], the interpreter returns [1,2,3,4] instead of [2,4]. The introduction of a new variable, below called u, is necessary to get this to work:
find :: Eq a => a -> [(a,b)] -> [b]
find k t = [v | (u,v) <- t, k == u]
Does anyone know why the first variant does not produce the desired result?
From the Haskell 98 Report:
As usual, bindings in list
comprehensions can shadow those in
outer scopes; for example:
[ x | x <- x, x <- x ] = [ z | y <- x, z <- y]
One other point: if you compile with -Wall (or specifically with -fwarn-name-shadowing) you'll get the following warning:
Warning: This binding for `k' shadows the existing binding
bound at Shadowing.hs:4:5
Using -Wall is usually a good idea—it will often highlight what's going on in potentially confusing situations like this.
The pattern match (k,v) <- t in the first example creates two new local variables v and k that are populated with the contents of the tuple t. The pattern match doesn't compare the contents of t against the already existing variable k, it creates a new variable k (which hides the outer one).
Generally there is never any "variable substitution" happening in a pattern, any variable names in a pattern always create new local variables.
You can only pattern match on literals and constructors.
You can't match on variables.
Read more here.
That being said, you may be interested in view patterns.