开发者

Pure functional using F#

Is it possible to force F# to behave like a pure functional language like Haskell? Maybe u开发者_如何学编程sing some compiler directives?

PS: since I come from a C/C++ background, I want to force myself to learn functional programming without learning Haskell :)


You can't force this behavior in F#, but as Brian said discipline is your best friend. E.g. don't use mutable, for or while loops, ref keywords, etc. Also stick with purely immutable data structures (discriminated union, list, tuple, map, etc). If you need to do IO at some point, architect your program so that they are separated from your purely functional code.

Don't forget functional programming is all about limiting and isolating side-effects.


Nope, sorry. You just have to use discipline.


If you're anything like me, you will probably avoid the 'good stuff' if you don't force yourself to use Haskell instead of F# and use Haskell as idiomatically as you can. Using algebraic data types instead of objects, learning to love laziness, embracing the monad, and more are much more of a core part of Haskell, and arguably some of the finer points (in my opinion) of pure functional programming.

F# doesn't have as steep of a learning curve in many ways, but you sound like you are learning it for fun, so why not challenge yourself anyways? I can attest that moving to F# after using Haskell can give you a much better feel for how F# in general ought to be used anyways.

Food for thought.


The purely functional aspects of Haskell are fundamental to the language. You can't just transplant it between languages. It leads to major design decisions — for instance, Haskell's purely functional nature led to the invention of the IO monad. F# does not have such an "escape-valve" for stateful computation.

Also, learning to program in a language that supports functional programming but doesn't absolutely enforce it might actually be instructive. Many people get confused between Haskell's individual design decisions (e.g. the IO monad, to hit the big example again) and how functional programming works in general.

In short: No, you can't this. But what you can do is watch very carefully and question everything you do that involves maintaining state and sequencing operations to make sure that there isn't a more pure abstraction you're missing.


No. Currently F# compiler cannot do this checking.

Why not just start writing some F# program to learn functional programming? I know a few people who learned ML/Ocaml/F# first and then moved to Haskell.

Then you will have a better understanding of purity. (If you really haven't touched any functional programming language before, your understanding of pure functional could be superficial. )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜