5

I'm trying to write Taylor series in F#. Have a look at my code

let rec iter a b f i = 
    if a > b then i;
    else f a (iter (a+1) b f i) 
let sum a b = iter a b (+) 0  // from 0
// e^x = 1 + x + (x^2)/2 + ... (x^n)/n! + ...
let fact n = iter 1 n (*) 1 // factorial
let pow x n = iter 1 n (fun n acc -> acc * x) 1 
let exp x =
             iter 0 x
                (fun n acc ->
                     acc + (pow x n) / float (fact n)) 0

In the last row I am trying cast int fact n to float, but seems like I'm wrong because this code isn't compileable :( Am I doing the right algorithm?

Can I call my code functional-first?

Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
  • 2
    Let me second Fyodor's comment about providing the *exact* error message when you ask "why doesn't this code work?" or similar questions. It removes a lot of the guesswork from writing answers, and ensures that you're more likely to get good answers to your question because more people will be able to figure it out without having to guess. – rmunn Mar 28 '17 at 23:58
  • @rmunn thank for your comment! Next time i will mention exact error message, my bad. – Dmytro Zhluktenko Mar 29 '17 at 22:18

1 Answers1

6

The code doesn't compile, because:

  • You're trying to divide an integer pow x n by a float. Division has to have operands of the same type.
  • You're specifying the terminal case of the wrong type. Literal 0 is integer. If you want float zero, use 0.0 or abbreviated 0.

Try this:

let exp x =
         iter 0 x
            (fun n acc ->
                 acc + float (pow x n) / float (fact n)) 0.

P.S. In the future, please provide the exact error messages and/or unexpected results that you're getting. Simply saying "doesn't work" is not a good description of a problem.

Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
  • You are awesome! For some reason I was thinking that you need only one float element in your expression and F# will make result float. Now my problem is solved and I'm good to go with my code! TY – Dmytro Zhluktenko Mar 29 '17 at 22:20
  • 1
    That "some reason" is probably your past experience with C-like languages, where automatic type widening is the norm. – Fyodor Soikin Mar 29 '17 at 22:58
  • 1
    If my answer helped you, please take a moment to mark it as "accepted" by clicking the gray checkmark to the left. – Fyodor Soikin Mar 29 '17 at 22:59