Simplify a continued fraction

J, 8 5 bytes

Same as this, but uses a build-in for rationals.

Argument is {a0,a1,a2,a3,...} as a list of J extended precision rational numbers. Result is the fraction as a J extended precision rational number.

(+%)/

(+%) the plus-the-reciprocal-of

/ reduction over

Try it online!

-3 thanks to miles.


Haskell, 37 36 18 bytes

foldr1$(.(1/)).(+)

This function expects Haskell's Ratio type as input. Usage example:

Prelude Data.Ratio> ( foldr1$(.(1/)).(+) )  [4%1,2,1,3,1,2] 
170 % 39

Note: one explicit Ratio in the input list (4%1) is enough, the type systems figures out that the others have to be Ratios, too.

Edit: @Lynn saved a byte. Thanks!

Edit II: removed the import (see this discussion on meta).


GolfScript, 13 bytes

~]-1%{\-1?+}*

Try it online!

Yay for GolfScript's hidden rationals. :)

Explanation

GolfScript's only "official" number type is integers. But the exponentiation operator doesn't cast its result to integer and conveniently the native result of an integer exponentiation in Ruby (the language of GolfScript's interpreter) is a rational number. So we can easily get fractions by raising something to the power of -1. Conveniently, we want reciprocals anyway...

~]     # Evaluate input and wrap all a_i in a list.
-1%    # Reverse the list so that a_n is at the start and a_0 at the end.
{      # Fold... (apply this block to each element from a_n-1 down to a_0, with
       # the previous result on the stack)
  \    #   Swap previous result with current a_i.
  -1?  #   Raise previous result to the power of -1, computing its reciprocal
       #   as a rational number.
  +    #   Add a_i.
}*