Created
April 4, 2010 14:24
-
-
Save hakunin/355427 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # How learning Haskell changed my programming skill | |
| # Pascal's triangle BEFORE Haskell: | |
| def triangle_before_haskell iterations | |
| rows = [] | |
| iterations.times { |r| | |
| new_row = [1] | |
| if r >= 1 | |
| row = rows[r-1] | |
| (r-1).times { |i| | |
| new_row << row[i]+row[i+1] | |
| } | |
| new_row << 1 | |
| end | |
| rows << new_row | |
| } | |
| rows | |
| end | |
| # took me 20 minutes or more, not knowing how to operate | |
| # on arrays properly is the main issue here, also the code | |
| # is not recursive | |
| # Pascal's triangle AFTER learnign some Haskell: | |
| def triangle depth, last_row = [1], triangle = [last_row] | |
| if depth == 1 | |
| triangle | |
| else | |
| row = [1] + last_row.enum_cons(2).map { |a, b| a+b } + [1] | |
| triangle(depth-1, row, triangle+[row]) | |
| end | |
| end | |
| # after learning some Haskell, this took me only 5 minutes to write. | |
| # the code is recursive, much cleaner and since learning Haskell | |
| # I know that it is very important to know what your language does for you | |
| # both produce the same output | |
| triangle_before_haskell(8).each { |row| puts row.inspect } | |
| triangle(8).each { |row| puts row.inspect } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment