开发者

Fascinated by FP but still think imperative, how do I think functional? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 10 years ago.

Like most ppl, I started with and still do a lot of imperative code(mostly Java, Ruby, Javascript).

I've never been a big fan of OO, either because I never understood it properly or because I don't think OO.

Got my first glimpse of FP via javascript, passing functions around, closures, etc. Have been in love with FP since then.

Recently, I've developed interest in Clojure (and may be Scala) and someday might even have a go at Haskell. I like what I see in the functional approach, but how do I think functional? I've been doing imperative stuff for the past 3-4 yrs and my brain tends to think imperative while approaching a 开发者_开发技巧problem.

How can I unlearn the imperative style(do I need to?) and think more functionally ?


No. Don't unlearn imperative style as you'll still need it. Even many well-done FP libraries look somewhat imperative under the covers. It's better to think in terms of adding FP to your list of tools and techniques rather going full-metal with one technique or the other.

Now, as to how you go about learning the FP style? Toy projects - or utility project you write for your own use. Or hell, write yourself yet another blog - but with a twist! The key thing, as was stated above, is practice. When doing so, avoid shared state. Strive for purity (that is, avoid side effects) in as many places as you can. Use closures, pattern matching (if the language supports it) and lambda functions. Think in terms of functions being first-class data types in your program - take them as input and return them as output. The list goes on, but you'll see the same concepts repeated time and again if you're watching for them.

If you feel you need a gentle nudge in this regard, use a tool (language) that encourages the FP style such as F# or Scala.

If you feel you need more of a "tough love" kind of help, reach for Haskell :)

Otherwise use the tool of your choice and just keep FP concepts (above) in mind. If you decide go this route there's a pretty good book called Real-World Functional Programming that uses F# and C# to illustrate techniques that apply in both a "mostly" FP language (F#) and a "mostly" OO language C#.


Go for Haskell. Because it's pure you are forced to think functional. In F# or Scala you still can write very imperative code. I strongly recommend the book by Graham Hutton on Haskell.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜