Locally defined types and easier-to-read algorithms
-
Thursday, February 28, 2013 12:19 AM
I've got a function that traverses a graph and builds up a list of nodes and their properties. Each one can be represented using a tuple with parts like...
(nodeName, parent, childCount, depth, ancestors, isPartOfCycle, minimumDepthOfChildren)
The code starts to get tough to read since each part of the tuple isn't labeled and some of the tuple components have the same data type. It also takes a lot of concentration on my part when I write the code to make sure I am putting the right data into each piece of the tuple and labeling it correctly when I pull it out. One solution to this is to define a record like...
let NodeInfo = { name:string; parent: NodeInfo; childCount:int; ancestors: NodeInfo list; etc.
...and then use this record instead of a tuple. But this record type isn't needed anywhere outside the function and it bothers me to have to define it more globally. I wish I could define it inside the function and then perhaps the compiler would complain if I ever attempted to return it from the function or use it where it isn't within scope. I could create a module whose sole purpose is to hold my function and the types that function needs - many of which would be marked private - but this seems kind of heavyweight.
What strategies can I use to make my code easier to understand and write? Is the only viable solution defining a record? Is there any way to label the parts or components of a tuple?
All Replies
-
Thursday, February 28, 2013 1:44 PM
Probably the best you could do is to define a record in local module. I don't think it's too heavyweight b/c you can define a module with only one record.
I think there's no way to 'label' tuple elements. Actually a record is kind of tuple with named fields but you cannot define type inside a function scope.
Also you could use signature file (*.fsi) as an external interface for your library and list there only types and functions you want to open to outside world.
Petr
- Proposed As Answer by Keith BattocchiMicrosoft Contingent Staff, Moderator Thursday, March 21, 2013 5:58 AM
- Marked As Answer by JustinMag Monday, April 01, 2013 8:19 PM