Using non-deterministic functions is unavoidable in applications that talk to the real world. Making a clear separation between deterministic and non-deterministic is important.
Haskell has the IO monad that sets the impure context by looking at which we know that everything outside of it is pure. Which is nice, if you ask me, when it comes to unit testing one can tell which part of their code is ultimately testable and which is not.
I could not find anything that allows separating the two in F#. Does it mean there is just no way to do that?
The distinction between deterministic and non-deterministic function is not captured by the F# type system, but a typical F# system that needs to deal with non-determinism would use some structure (or "design pattern") that clearly separates the two.
If your core model is some computation that does not interact with the world (you only need to collect inputs and run the computation), then you can write most of your code as functional transformations on immutable data structures and then invoke these from some "main" I/O loop.
If you're writing some highly interactive or reactive application then you can use F# agents (here is an introductory article) and structure your application so that the non-determinism is safely contained in individual agents (see more about agent-based architectures)
F# is based on OCaml, and much like OCaml it isn't pure FP. I don't believe there is away to accomplish your goal in either language.
One way to manage it could be in making up a nominal type that would represent the notion of the real world and make sure each non-deterministic function takes its singleton as a parameter. This way all dependent functions would have to pass it on along the line. This makes a strong distinction between the two at a cost of some discipline and a bit of extra typing. Good thing about this approach is that it can verified by the compiler given necessary conditions are met.
Related
Actually sometimes you are required to write some custom code to achieve some functionality, there would be 2 possible approaches there:
make your implementation by joining already given methods of
Objective-c
write your custom code
At that point I am confused which code base is better(in performance), that can only be decided if I luckily find Time-Complexity of Objective-c methods. So is there any way to know about it?
There are a lot of methods and functions you can call in the SDKs for iOS (and other Apple platforms), so this question is perhaps excessively broad.
But a discussion of time complexity is usually about algorithmic complexity, so we can restrict our scope to those calls that are the building blocks of algorithms where we measure time as a function of input size — that is, things like collection operations rather than, say, UIApplication registerForRemoteNotifications.
By and large, however, Apple doesn't talk much about the computational complexity of the high-level data structures in Cocoa. This probably has something do with Cocoa's design goals being strongly in favor of encapsulation, with simple interfaces hiding powerful, dynamic, and possibly adaptable implementations. Examining CoreFoundation — the open source implementations underlying the central bits of Cocoa, like collections — bears this out. Here's a great writeup on how NSArray is sometimes O(1) and sometimes not.
There's certainly something to be said for a philosophy where you're not supposed to care about the complexity of the tools you're using — tell it what you want to do, not how you want it done, and let it optimize performance for you, because it can second-guess you better than you can second-guess yourself. It goes well with a philosophy of avoiding premature optimization.
On the other hand, there's also some sense to a philosophy of having basic building blocks of enforced, predictable complexity so that you can more easily plan the complexity of the algorithms you build from them. Just to show that Apple seems to do it both ways, it appears this is the philosophy of choice for the Swift standard library.
Data and functions in Rascal can scatter in different source files, and when imported are merged accordingly. In other words, Rascal supports open data and open functions. So Rascal solves the expression problem? Is it designed so as to do?
I think to write that Rascal "solves" the expression problem, is a bit strong, but you could say that you can easily write openly extensible implementations of expression grammars in it. It was designed exactly for this, see http://www.rascal-mpl.org/from-functions-to-term-rewriting-and-back/
On the one hand, one can write programs which do not suffer from the expression problem in Rascal, precisely for the reason you said: both data and functions are openly extensible, and they work together via dynamically dispatching via pattern matching.
On the other hand, It is pretty easy to write non-extensible implementations as well in Rascal. In particular when using the current visit or switch statements, which are not openly extensible. Also if you write a set of mutually recursive functions, it may be pretty hard to extend them in an unforeseen manner. We are also working on language features to cover extending those kinds of designs. That is for the future.
(I'm using the word "workflow" - not in the sense of async workflows - but rather in the "git workflow" sense, that is, how you use it as part of your development)
Having played around with F# for a while, I've started developing my first F# app. I'm from c#/vb. Having watched various demos/talks - rightly or wrongly- I've started off using fsi as the main development "engine" and work up stuff within that area. If I hit a problem which I need to debug, I tend to break out the problematic function into smaller bits and check those work to try and debug the problem.
However, In order to keep the amount of code manageable in fsi, once I am happy with what I have done, I the move it into a .fs and #load the .fs back into fsi. As the app gets bigger, this can begin to feel a bit clunky since when I need to refactor, I end up having to bring back in content from the fs file change it run stuff to get something working again, before pushing the code back out into the .fs file. Further this style isn't really a test first approach and so I am not getting the benefit of building a set of tests. (I can also miss the ability to set breakpoints/step the code which, istm in certain situations e.g. recursion, can be quicker for diagnosing errors than breaking out parts of a function - though maybe this is available in VS11 and I'm not setup right) .. so I think I'm perhaps not doing things optimally or else not thinking about things in the right way.
I was wondering if others could offer how they develop apps. Do you primarily use fsi or do you start with tdd. Should the tdd approach be the primary dev vehicle and FSI used more selectively to aid in the, say, implementation of more complex algorithms, data exploration etc etc
I have looked at this question and obviously it helpfully points to various tdd frameworks for F#, but I'd still be interested to find out the workflow of seasoned F# developers.
Many thx
S
I think you're on the right track.
Development process is a matter of taste. I'll share my approach anyway.
Start by a few fs files. Each file represents a module, which consists of a group of functions closely related to each other. It doesn't have to be precise from beginning; you often move stuffs between modules.
Create a few fsx files for quick testing once skeleton of the modules is ready.
Create a test project and set up NuGet packages. I often use NUnit and FsUnit together.
Whenever fsx scripting gives correct results, move them to test cases. Do this repeatedly.
Include a Program.fs into the main project and compile to executable in order to debug if needed.
In general, F# REPL is the main development engine. It gives me instant feedbacks and allows incremental changes, which are very helpful in prototyping. In F#, TDD is less critical since bug rate is much lower than in other languages. And I don't test everything, just focus on main functionalities and ensure a high test coverage. Using testdriven.net add-in or Visual Studio 2012 Premium and Ultimate can give you useful statistics on test coverage.
Using F# REPL and TDD, I almost never have to use debugging. Whenever there is a wrong behaviour, I stop and think. Since your codes don't have side effects, you can reason on them easily. In many times reasoning and a few printing commands can give me the right answer.
You can use TDD in F# REPL with Unquote and FsCheck. The former offers testing via quotations, which is quite impressive. The latter uses random testing approach which is attractive in handling corner cases of your codes. I find it really useful when your programs have to satisfy certain properties. However, it may take time to learn to use these frameworks properly.
pad gave a great answer that is very practical and useful for a person new to F#. I will give a different means so that others don't think there is only one way F#'ers do it.
Note: If you are very new to programming, then stick with pad's answer, it is much better for a new programmer.
In the Object Oriented world one thinks with objects and in such languages I would start with writing objects down on paper and working with various diagrams such as use-case, state transition, sequence diagram, etc., until I felt I had enough to start creating objects in C# cs files, fleshing out the objects with methods, properties, events, etc.
In the functional world I typically start with abstract concepts and convert them into discriminated unions (DU) in an F# fs file, skipping the use of a REPL, i.e. F# Interactive, and then start adding a few functions. After I have a few functions I set up a test project using NUnit and FsUnit via NuGet. Since the DU are abstract, the test cases are typically harder to write, so I create printers for the DU and then insert them into the test case where I capture result output from the printer in the NUnit tool, for cut and paste back into the test case making changes as necessary. See these for examples of why I don't write them from scratch by hand.
Once I have the abstract DU done, I then can move onto the code to convert the human/concrete form into the abstract DU and convert the abstract DU into human/concrete form. In some cases these would be parsers and pretty printers.
The main point I am trying to make is that I don't focus on the tools I use but on the abstract concept of the problem and bring the tools in when needed.
I will note that I also program in PROLOG and there I do start with the REPL and move the code to a store once the logic works. So I am not opposed to using a REPL, it's just a different way of approaching the problem.
EDIT
Per a request by Ken for an example.
See: Discriminated Unions (F#) and look for the section
Using Discriminated Unions Instead of Object Hierarchies
So instead of a base type of shape with inherited types of Circle, EquilateralTriangle, Square and Rectangle one would create a discriminated Union as noted:
type Shape =
| Circle of float
| EquilateralTriangle of double
| Square of double
| Rectangle of double * double
As your question would make for a much better independent question and get answers with much better detail than I can give, I would suggest you ask it.
Also if you search for info on this also search with the following substitutions for discriminated union (DU):
Algebraic data type
Generalized algebraic data type (GADT)
Tagged union
Variant
variant record
disjoint union
sum type
I want to create a simple "multi-agent" system consisting of three agents. For each agent, there is a type created encapsulating the mailbox processor. There are attributes common to all the agents (position, id etc.) and functions (sendMessage, move) and agents differs from each other with the implementation of mailbox processors (how the messages are processed). In addition, they may differ by other functions specific to particular agents. Every agent should also contain (as one of its attribute) a list of other agents, to whom it will be sending the messages. This is a just very simple model based on which I plan to play with the mailbox processors in F#.
In OOP, this would mean creating an agent interface (or abstract class), and all the particular agents would be inherited from this interface with their own implementation.
I know OOP is possible in F#, however I would rather stick to pure functional design. However, it seems to me that OOP is the most suitable approach in this case. I would be glad if you could give me any idea with respect to functional (F#) design? Thank you.
First of all, the functional style and object-oriented style in F# are not really in conflict.
Functional style consists of using immutable types, pure functions without side-effects and F# data types such as discriminated unions, functions etc.
Object-oriented style is more focused on how you organize code (using classes and interfaces), but the code can still be purely functional without using any mutable state.
In agent-based systems, it makes a good sense to use functional style in the implementation of the agent, but to organize the agents using classes. I think this is probably the best practice in F# (see also this article on encapsulating F# agents on MSDN).
In your example, you're saying that an agent keeps a list of other agents that it sends messages to. There are a few alternatives worth considering (if you want to avoid interfaces):
Expose an F# event (Event<'T>). This way, the agent simply exposes a notification and does not have to explicitly manage a list of other agents (and this design also allows other types of subscribers).
Keep a list of functions. If you just need to send messages to other agents, then you essentially need just an interface with a single method. In that case, you could keep a list of functions such as
Message -> unit.
I generally prefer exposing events - this way, the system is less tightly coupled and you can more easily compose agents in various ways (they do not have to implement a specific interface to be composed). This article discusses agent-based architectures from a higher-level perspective, and may be useful too.
Why would you want to stick to a pure functional design ? F# allows a clean combination of functional and OOP principles and I would make use of both mechanisms and leverage the power of the language.
If you want to combine the functional and OOP aspects, I would start by making your objects immutable. Thus you're using objects, but in a functional paradigm.
You have come up with an OOD, is it surprising that an OOP solution seems the most natural?
If you rewrote the design description with processes, and data transformations in mind it would naturally fall out as a FP design, and sound really awkward in OO with lots of 'er classes. As it is there is almost zero description of the types of data or what transformations need to take place. At first glance I would say an agent is a function of three arguments a mailbox, a message handler(or list of message handlers), and a list of other agents' mailboxes to contact. If future dispatch is based on the message then the message handler is a function of two args. the message, and the list of mailboxes.
I'm still new to OOP, and the way I initially perceived it was to throw alot of procedural looking code inside of objects, and think I'd done my job. But as I've spent the last few weeks doing alot of thinking, reading, and coding (and looking at good code, which is a hugely under-rated resource), I believe I'm starting to grasp the different outlook. It's really just a matter of clarity, simplicity, and organization once you get down to it.
But now I'm starting to look at things as objects that are not as black and white a slamdunk case for being an object. For example, I have a parser, and usually the parser returns some strings that I have to deal with. But it has one specialized case where it has to return an array, and what goes in that array and how it's formatted has specialized rules. This only amounts to two lines plus one method of code, but this code sticks out to me as not being cleanly fitting in the Parser class, and I want to turn it into its own "ActionArray" object.
But is it going to far? Has OOP become a hammer that is making me look at everything like a nail? Is it possible to go too far with turning things into objects?
It's your call, but you should think of objects as real life objects.
Take for example a car. You could describe a car with different objects:
Engine
Wheels
Chassis
Or you could describe a car with just one object:
Engine
You can keep it simple and stupid or you can spread the dependency to different objects.
As a general guideline, I think Sesame Street says it best: you need an new object when "one of these things is not like the others".
Listen to your code. If it is telling you that your objects are becoming polluted with non-essential state and behavior (and thus violating the "Single Responsibility Principle"), or that one part of your object has a rate of change that is different from the rest, and so on, it is telling you that you are missing an object.
Do the simplest thing that could possibly work. When that no longer works, do the next simplest thing. And so on. In general, this means that a system tends to move from fewer, larger objects to more, smaller objects; but not always.
There are a number of great resources for OO design. In addition to the ones already mentioned, I highly recommend Smalltalk Best Practice Patterns and Implementation Patterns by Kent Beck. They use Smalltalk and Java examples, respectively, but I find the principles translate quite well to other OO languages.
Design patterns are your friend. A class rarely exists in a vacuum. It interacts with other classes, and the mechanisms by which your classes are coupled together is going to directly affect your ability to modify your code in the future. With poor class design, a change that you make in one class may ripple down and force changes in other classes, which cause you to have to change other classes, etc.
Design patterns force you to think about how classes relate to each other. For example, your Parser class might choose to implement the Strategy design pattern to abstract out the mechanism for parsing. You might decide to create your Parser as a Template design pattern, and then have each actual instance of the Parser complete the template.
The original book on Design Patters (Design Patterns: Elements of Reusable Object-Oriented Software is excellent, but can be dense and intimidating reading if you are new to OOP. A more accessible book (and specific to Ruby) might be Design Patterns in Ruby, which has a nice introduction to design patterns, and talks about the Ruby way of implementing those patterns.
Object oriented programming is a pretty tricky tool. Many people today are getting into the same conflict, by forgetting the fundamental OOP purpose, which is improving code maintainability.
You can always brainstorm about your future OO code reusability and maintainability, and decide yourself if it's the best way to go. Take look at this interesting study:
Potok, Thomas; Mladen Vouk, Andy Rindos (1999). "Productivity Analysis of Object-Oriented Software Developed in a Commercial Environment"