25thOctober2017, 03:39 PM  #1 
Member
Join Date: Jun 2017
Posts: 650

The Coding Thread
What about a little thread where we post and solve small, cool problems to be solved computationally?
I'll kick things off with this one: Write a function that computes the sum of the n first Fibonacci numbers. Print some cases, e.g. n =10, n = 100, n = 10,000. Preferably explain the idea of the algorithm as well 
25thOctober2017, 04:33 PM  #2 
Condescending Bastard
Join Date: Dec 2009
Posts: 7,423

Re: The Coding Thread
I'm confused, you want a Fibonacci sequence that starts with something other than 1 (lets call that 'x') and goes to n?
So if 'n' = 10.5 then 'x' = 0.5 Spoiler:
But the thing is if 'n' is 10 or 10.5 or basically any number that isn't part of the usual sequence then I don't think the reverse sequence is ever going to stop so there will be no "first" number. I just pulled 0.5 out of my ass and calculated up.
__________________
Deadlier, Sillier and more Perverted. 
25thOctober2017, 04:39 PM  #3 
Member
Join Date: Jun 2017
Posts: 650

Re: The Coding Thread
no, I mean the usual Fibonacci numbers. So n is an integer.
If it's the 10,000 that's confusing you it's supposed to be 10000, not 10.000. I hear they like to use commas to separate zeros over there in US so I went with that. 
25thOctober2017, 04:45 PM  #4 
Light
Join Date: Apr 2010
Location: Calm Stillness
Posts: 4,501

Re: The Coding Thread
fibsum = 0
x = 0 y = 1 z = 0 for loop 5{ z = x + y x = y y = z fibsum += z return z} print fibsum: 19 1, 2, 3, 5, 8 end 
25thOctober2017, 06:10 PM  #5 
Member
Join Date: Jun 2017
Posts: 650

Re: The Coding Thread
lol I just realized n=10000 might be a bit ambitious. It makes for an interesting challenge though

25thOctober2017, 07:51 PM  #6 
Member
Join Date: May 2016
Posts: 246

Re: The Coding Thread
function fs =FibSum(n)
phi=0.5*(1+sqrt(5)); %golden ratio fibvec=1:n; fibvec=(phi.^fibvec)/sqrt(5); fibvec=round(fibvec); %The fibonnaci numbers fs=sum(fibvec); end I found a closed expression for fibonacci numbers on wikipedia. Vectorized the code for efficiency, and let it run in matlab. Calculation performed in ~8e4 sec. on my laptop shows that FibSum(1000)=1.1380e+209. FibSum(10000) doesn't take longer, but gives infinity as a result. There must be a way to keep the result finite I guess by playing with different number representations or so, but I suppose that for all kinds of practical purposes this number is effectively infinity anyway. 
25thOctober2017, 09:08 PM  #7 
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Fibonacci Sequence at Rosetta Code
I suppose this is a good place to introduce memoization into the conversation ... especially when one arbitrarily picks n=10000. Anaphoric programming might be applied to generating the fibonnaci sequence as well as streams. It would be nice if TryScheme, TryAPL, and others allowed one to represent a runnable program as a link, but Papert Logo does, so ... To generate and see a Fibonacci sequence, Click me! 
25thOctober2017, 09:27 PM  #8  
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Quote:


26thOctober2017, 09:48 AM  #9 
Member
Join Date: Jun 2017
Posts: 650

Re: The Coding Thread
A little solution I put together last night. The idea is pretty straightforward; since we're dealing with big numbers, I use vectors of digits to represent them. To add them I use the good ol' manual addition method we all learned as small kids. The rest is pretty much the usual Fibonacci sequence generation as in Anime's post.
Spoiler:
output: n = 10: 143 n = 100: 927372692193078999175 n = 1000: Spoiler:
n=10000: Spoiler:
By no means an efficient implementation, but runs in a second or two. There should probably be a way of reducing the no. of operations by noting that e.g. 21 + 13 + 8 + 5 + 3 + 2 + 1 + 1 = 2(21) + 2(5) + 2 
26thOctober2017, 07:04 PM  #10  
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Quote:
I suspect that a `solution' in which 1 x fib(n) rectangles are stacked sidebyside would help the human eye see/spot the common factors. The difference between prime factorization and the sort we'd want to use here is that prime factorization entails multiplication whereas in this case we want to represent sums as the sum of two or more integers with one of these integers being the sum of the previous stage. (note: if we were going to be using this algorithm A LOT  such as in some cyrptographic algorithm  it might bear such computational optimization. I suspect that it's performance above and beyond an algorithm using memoization would end up not worth the optimization effort.) Dynamic languages (python, ruby, javaScript, all the lisps, etc.) offer an exploit in the form of `eval' which allows a `program' or symbolic expression to be programatically composed/constructed THEN evaluated at run time. As the lisps (including Scheme implementations and some Logos) allow both addition and multiplication to be performed en mass  rather than pasting arguments together pairwise as per infix inflix notation  what we think of as an integer MAY be represented as subexpressions which evaluate to those integers. To wit: 1 + 2 ==> (+ 1 2) 1 + 2 + 3 ==> (+ 1 2 3) 21 + 13 + 8 + 5 + 3 + 2 + 1 + 1 ==> (+ 21 13 8 5 3 2 1 1) OR, via the magic of both infix and dynamic evaluation (eval (cons '+ '(21 13 8 5 3 2 1 1))) OR, if we replace integers with expressions summingto Code:
; note: best viewed inside the code block so same number line up vertically. ; All of our integers can be represented as sums of integers (+ (+ 21 13 8 5 3 2 1) (+ 13 8 5 3 2 1) (+ 13 8 5 3 2 1) (+ 8 5 3 2 1) (+ 5 3 2 1) (+ 3 2 1) (+ 2 1) (+ 1) (+) ; the additive identity ) 

27thOctober2017, 11:40 AM  #11 
Member
Join Date: Jun 2017
Posts: 650

Re: The Coding Thread
Hmm, actually, the whole thing is simpler than I thought. In fact, if you let S_n denote the sum of all Fibonacci numbers F_k for k=1, 2, ... n, then
S_n = F_{n + 2}  1 I.e. it's just the Fibonacci number two steps ahead, minus 1. This is easy to prove using induction. 
28thOctober2017, 12:01 AM  #12 
Member
Join Date: Jun 2017
Posts: 650

Re: The Coding Thread
Have no clue if it's difficult or not (probably is) but one I thought of right now:
Compute the 10 most significant digits of (1 / pi) raised to power of 1000 
1stNovember2017, 09:48 PM  #13  
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Quote:
As you've expressed a disdain for OOP perhaps you'd like to use oneormore nonOOP paradigms to use code to make your point? Personally, my own bents and proclivities find me preferring to expand the audience of this thread via accessibility breadth over math/CS formal scicneces depth. To wit, how might oneormore of us participants dePICT the results of this `induction' via graphicovisual means which would allow those with dominant right hemispheres to SEE what you mean while absolving them of the responsibility or multiple intelligences configuration to either follow your textual narrative or the algorithmic logic of your code ... or some blend of BOTH? For instance, what if the unique additive factors of the Fibonacci were presented as 1xN rectangles of either RGB (EG like a 3 color map) or a unique color via, say, 24color ... then stacked endtoend vertically, horizontally, or such so the the human eye could readily notice what your inductive process by itself might not necessarily reveal or make apparent to such Visual Thinkers? 

2ndNovember2017, 01:09 AM  #14  
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Quote:
The relative numeric values of neighboring Fibonacci numbers are represented by lengths perceptible to the naked eye sans any notion of numbers ... which can trigger eyes glazing over in some people. 

2ndNovember2017, 11:22 AM  #15  
Member
Join Date: Jun 2017
Posts: 650

Re: The Coding Thread
Quote:
So for this case it's quite elementary. For the base case, we can see that e.g. 1 + 1 + 2 + 3 = 7 The Fib number two steps ahead of 3 is 8, and 81 = 7. So assuming ncase holds, we prove n + 1. This is also easy: That's pretty much it. So basically, any algorithm which can generate large Fib numbers is sufficient to solve the problem. 

3rdNovember2017, 07:28 PM  #16  
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Quote:
Perhaps we could make a new number line centered at infinity rather than zero. Then we could mark all the Fibonacci numbers, factorials, Hailstone sequence numbers, and such as we move away from infinity heading towards 0? 

4thNovember2017, 06:00 PM  #17 
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Yes, `mathematical' induction as contrasted with philosophical induction and inductive reasoning.
Neither of which I'd want a curious INTP lurker of this thread to have to exclude as per whatever biases they bring as a member of the viewing audience. I wouldn't want this hypothetical lurker to see a Sigma symbol without experiencing `meh' or outright repugnance, but  to reiterate, if not reSUMerize perhaps by reSigmafying  I'm more interested in promoting accessibility breadth than an overspecialized depth which panders to the pro forma sciences of mathematics and Comp Sci. while discouraging those motivated by curiosity to try their hand at the accessible, practical art of `coding'. So, once again ... "As you've expressed a disdain for OOP perhaps you'd like to use oneormore nonOOP paradigms to use code to make your point?" In other words, can you implement the sigma function via oneormore languages capable of exploiting the functional paradigm ... which, arguably, IS the paradigm most `mathy' and capable of implementing both Capital Sigma and it's closeenough cousin the Capital Pi function? I'm of the mind that had computers been available when the terms Algebra and Algorithm forks of the name alKhwarizmi algorithmic methods would have outevolved merely `algebraic'  whatever this adjective would come to mean in the shadow of algorithms  ones. For those unfamiliar with the functional paradigm, had we a sequence or stream of numbers 1 thru n  as the limits of both/either the capital sigma or capital pi function  we could apply any arbitrary function (EG even unnamed functions in some languages capable of functional programming) to this sequence to obtain/generate the results we want. I suspect many coders  and more than a few tentative, potential coders  can spot the deepstructural semantics underpinning the surfacestructural Capital Sigma symbol when they see it. I'll whip off a quick and dirty implementation of a function attributed to a ancient Greek for finding the distance between two dangling ends of any Lshape wanting to become a triGon via a method attributed to yet another ancient Greek. Code:
; < this is a comment symbol ; the following symbolic expression (EG `code') was tested via the ; elisp REPL of GNU Emacs for Windows . ; With minor changes it can be made to work in Gimp's scriptfu,, ; S7 scheme as implemented via GRACE and Common Music, ; GUILE  as the official scripting language of GNU and Gnome  ; tryScheme ; scheme in general  via umpteen flavors  ; and, last but not least, Common Lisp ( ;< every symbolic expression begins with an opening paren (lambda (args) ; anonymous function taking an argument which is ; a list of arguments in this case (sqrt ; square root (apply '+ ; as a higherorder function, `apply' can be used to apply a ; lower order function  as a cats paw  to enlisted data (mapcar ; maps a function onto the first element of increasingly ; smaller instance of a list perpetually composed of the '(first ...) ; where `... = rest of list' until every element of the setcumlist ; has had the function mapped onto it. (lambda (n) ; first arg of mapcar. namely an anonymous function ... (* n n) ; whose algorithm entails the multiplication of n by n ) args ; second and final arg of mapcar ) ;mapcar ) ;apply ) ;sqrt ) ;lambda '(3 4) ; the list of args required by out outermost lambda ) ;closing paren matching the opening paren followed by a function ;;; end of DOCUMENTED, verbose version ;v terse, mathy oneliner version ( (lambda (args) (sqrt (apply '+ (mapcar (lambda (n)(* n n)) args)))) '(3 4) ) ;^ terse, mathy oneliner version ;; note: for terser still, check out APL, perhaps via tryAPL ;; note to Serac: for your 1 to n range check out APL's iota function: ;;v snarffed from: https://en.wikipedia.org/wiki/Iota ;; In some programming languages (e.g., A+, APL, C++, Go[6]) iota ;; (either as a lowercase symbol ι or as a keyword iota) is used to ;; represent and generate an array of consecutive integers. ;; For example, in APL ι4 gives 1 2 3 4. ;;^ snarffed from: https://en.wikipedia.org/wiki/Iota ;; ;v terse, mathy oneliner version generalizing our function to 3 args ((lambda (args) (sqrt (apply '+ (mapcar (lambda (n)(* n n)) args)))) '(2 3 5)) ;^ terse, mathy oneliner version generalizing our function to 3 args ;v version pandering to those mentally mutilated by either procedural or OOP ; both of which require the use of NAMES which induce nominalization, ; reification and other cognitive diseases. (fset ; function set. Set the name of a fuction. In scheme we would use `define' 'EuclideandistanceviaPythagoreantheorem ; symbol/name to bind to ; the following `value' (lambda (args) (sqrt (apply '+ (mapcar (lambda (n)(* n n)) args)))) ) ; fset ; having attached a `handle' we can use it as we'd use builtin functions (EuclideandistanceviaPythagoreantheorem '(3 4)) (EuclideandistanceviaPythagoreantheorem '(2 3 5)) ; Space reserved for Serac's capital Sigma function ; ; ; ; space reserved for the Fibonacci algorithm of Turnevies ; ; ; ; ; space reserved for Animekitty's delta function ; ; ; 
4thNovember2017, 07:29 PM  #18 
Member
Join Date: Jun 2017
Posts: 650

Re: The Coding Thread
I've actually been meaning to learn some functional programming languages. Haven't gotten to that yet though.
However, I don't view functional programming as the alternative to OOP. For example, the implementation I wrote above is basically imperative programming not relying on any OOP principles. Writing it in C, for example, would amount to pretty much the exact same implementation sans the use of std::vector. Also, I'm of the understanding that functional programming languages cannot be as efficient as imperative languages like C. You have to rely on recursion for example, which I imagine would be quite slow for, say, the Fibonacci problem above. 
4thNovember2017, 07:40 PM  #19  
Member
Join Date: Jun 2017
Posts: 650

Re: The Coding Thread
Quote:


5thNovember2017, 02:03 AM  #20  
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Quote:
It's not that the term `cat' is REQUIRED for me get the deep structural meaning of the creature addressed by that surfacestructural symbol; when the French say `chat' it's all the same to me. I'm trying to help others express THE SAME semantics as you may have learned in metaphorical `English' class via alternate languages. None of this is qua IS `required'; its preferential for/to me. Quote:
I responded to your use of capital sigma notation not by `completely rejecting'. To my mind there's a palpable difference between `completely rejecting' and by providing a few clues to how the deep structural MEANING can be exploited via programming languages exploiting various paradigms ... functional as an excellent choice for the decidedly mathy examples you've thus far presented. Rather than narrowing the universe of discourse as per what's implied by your rhetorical term `completely rejecting' I did  and presently do  attempt to broaden said universe of discourse and the assortment of programming languages whose `code' may be presented to all of us in the viewing audience. Quote:
Aside: In college my APL classmates and I all created a descriptive statistics package in a single line of APL code. I'll bet a java program implementing the same functionality would take that 400 lines of code you mentioned. Quote:
As I haven't done an exhaustive survey of all possible ways of `doing things', though have an eclectic assortment of familiar ways at my disposal, you'll probably find me sporting an eclectic mix rather than a `one right way' orthodoxical preference. If you learned `math' either BEFORE or as a corequisite to your programming/coding activities I can understand that FOR YOU there may be an ONLY WAY with which you are either familiar, comfortable, or both. Many CS programs in the US of A were either spawnedfrom or glommedonto extant math departments ... with predictable results. MIT did things a bit differently; they glommed their CS department onto the EE department ... with unheadbinding results visavis the way math weenies do programming. Math weenies didn't produce Scheme on a chip; math savvy engineers capable of both electrical engineering AND coding did. Not that you'd value this as a mathcentered or mathfavoring coder, but I do. I also value the pedagogical aspects of programming in that logical thinking can be promoted as a form of personal development by constructionism. Math expressions don't function as machines as well as computerimplemented algorithms do; many can LEARN precepts and concepts either BETTER or AT ALL by crafting algorithms via `code' whereas math symbolism leaves them cold, disenchanted, and without a worksforthem means of UNDERSTANDING. Though I have NO intention to remove math notation from YOUR toolbox, I do intend to present programming tools which others can ADD to their tool boxes. Thus my goading of you to start with your domain of comfort and confidence and reexpress the precepts and concepts you regard as `math' as `algorithms' expressed in `code' as the title of this/your thread suggests. I presented evidence that I understand the precepts and concepts as expressed in BOTH domains; I was hoping that you might do something similar. Though we may both obviously wax philosophical  rather than expressing via `code'  as the spirit moves us. Response 2: Have you heard of Metalinguistic abstaction? How about Genetic Algorithms? There are more than ONE wayS of dealing/coping with complexity and developing/generating complex systems, If somebody simply loves math I see no reason why they can't present Maxima code, Octave, gnuplot, or such. I'd still like to see you demonstrate mathematical induction via `code' in the programming language of your choice. Or ... how about using recursion in a programming language to demonstrate a recursive proof in mathematics? By way of a parting code snippet, here's how a generate a sequence of integers in my `text editor' of all things: Code:
(numbersequence 1 10) Code:
(mapcar (lambda (x)(list x (log x) (log10 x) (* x x)(* x x x) (expt 2 x))) (numbersequence 1 10)) Code:
(defun CapitalSigma (datapoints) "Add up the data points as if a math weenie using Capital Sigma" (apply '+ datapoints) ) ; here's a test case which results in 55 (CapitalSigma (numbersequence 1 10)) To return to induction ... I'm not sure I could demonstrate mathematical induction through programming though; I'd like to see it done. Can you humor me? Cheers! 

5thNovember2017, 04:15 PM  #21 
Member
Join Date: Jun 2017
Posts: 650

Re: The Coding Thread
I think in order to write a program that does inductive proofs, as with any mathematical proofs, it would have to be written in something that can do symbolic operations. Maybe Maxima might be a candidate for that. I really cannot think of any way you can do an inductive proof numerically.

5thNovember2017, 05:55 PM  #22  
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Quote:
This being a coding thread, if one were to use code snippets employing iteration  though perhaps not recursion, as this is what Maxima uses  one may very well NOT be able to exploit the methods underpinning wouldbe `mathematical' induction; thus my intuition that visualization methods  perhaps generated via iteration  might generate graphics which induce iNtuitive insights on par with induction. To wit, what if a rectangle were dePICTed which represents the n+2 term of your Capital Sigma expression merely deSCRIBEs? What if another  different colored rectangle  were to represent the n+1 term? What if a progression of these juxtapositions were presented sidebyside all the way down to n=1? I suspect that many necessarilysubjective beholders  INTPs among them/us  would behold the same semantic as that encoded in your mathematically inductive surfacestructural RHETORIC. I'm of the mindset that visual presentations SHOULD be granted equal status to rhetorical exposés presented in either `English' or any of the various notations used by math weenies. I also suspect that graphical rhetoric is more accessible over a broader range of INTPdom. Thus are my intuitive biases. 

5thNovember2017, 06:39 PM  #23 
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
To get back to `code'
Code:
; * org * * [[https://en.wikipedia.org/wiki/Inductionrecursion ][Inductionrecursion]] Those robust enough to copythenpaste the URL into the address bar of their web browser of choice may choose to do so. 
5thNovember2017, 07:31 PM  #24 
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Given that computation can be used to perform symbolic computation I'll recommend this freebie which I've used personally.
Though symbolic computation as a generic concept might be useful for coders who haven't tried it yet. 
6thNovember2017, 01:19 PM  #25 
Member
Join Date: Jun 2017
Posts: 650

Re: The Coding Thread
Hmm, maybe I should learn Common Lisp. I was thinking of Haskell but Lisp looks more useful

6thNovember2017, 08:20 PM  #26  
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Quote:
One seems trapped on a metaphysical side of a chasm of where monads ARE merely metaphysical. Then one has to find a way to manifest a sideeffect in the PHYSICAL World which most Real Worlders would think of as output. The lisps tend to support multiple programming paradigms; one can mix and match functional, OOP, imperative, declarative, and such. If one is sufficiently selfdisciplined and artistic enough to choose which paradigm to exploit at which which part in a program or a project then multiparadigm languages are A way to go. When I started using Touretsky's book back in '96 I was only familiar with the Logo member of the Lisp family and had AMX Lisp available to me via my Amiga. Since then I've worked with several Schemes  the uncommon lisps  and Emacs Lisp. Given your comfort and familiarity with mathematics I'd recommend The Algorithmic Language Scheme over Common Lisp for doing the exercises in the recommended book ... if you decide to use it. The Lisps maintain two name spaces, one for functions and another for data structures; the schemes better implement the spirit of Lisp  in which functions and data are thinly veiled versions of the same stuff  by using ONLY one name space. As I use emacs as my text editor for editing, I've also got a form of lisp available for pimping out said editor as I'm editing Lisp, scheme, logo ... whatever. If you need any more incentive for learning Scheme over Common Lisp, Scheme is used as a small footprint macro & scripting language for several apps. As I've noticed Ubuntu as your OS, you might use GIMP ... which uses the ScriptFu dialect of lisp as it's scripting/macro language. GUILE is also a dialect of Lisp and runs on all the distros of linux. Guix is a package manager based on scheme. In daily practice I use emacs lisp more than scheme as emacs lisp is a domainspecific language which allows one to automate text editing functionality via lisp. For example, I can both generate a post and parseintoparagrapslinesandwords a post via elisp more simply than with either common lisp or scheme. Though maybe Edwin, as distributed with MIT scheme, can do these sorts of things nearly as well; I don't really know. So ... Scheme might be better than Common Lisp for satisfying your objectives ... depending on what they all are. 

7thNovember2017, 12:57 AM  #27 
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread

8thNovember2017, 02:07 AM  #28 
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
From the Wikipedia page
"A recursive definition (or inductive definition) in mathematical logic and computer science is used to define the elements in a set in terms of other elements in the set (Aczel 1978:740ff). A recursive definition of a function defines values of the functions for some inputs in terms of the values of the same function for other inputs. For example, the factorial function n! is defined by the rules 0! = 1. (n+1)! = (n+1)·n!. This definition is valid for all n, because the recursion eventually reaches the base case of 0. The definition may also be thought of as giving a procedure describing how to construct the function n!, starting from n = 0 and proceeding onwards with n = 1, n = 2, n = 3 etc.." So by way of code, I'll present a recursive definition of the factorial function Code:
; emacs lisp which can readily be converted to Scheme (fset (function factorial) (lambda (n) ; https://en.wikipedia.org/wiki/Factorial "factorial of integer n, computed recursively as per mathematical induction and algorithmic recursion" (if (= n 0) 1 ; first clause of `if' is the true option, when n=0 (* n (factorial ( n 1))) ; 2nd clause of is is the false option ; this will recurse until n=0 ) ) ;lambda ) (insert "\n\n;;; Results ==> " (prin1tostring (mapcar 'factorial (numbersequence 0 6) ) )) ;;; Results ==> (1 1 2 6 24 120 720) Code:
; emacs lisp which can readily be converted to Scheme ; syntactic sugar option. we can use ! as a function name (fset (function !) ; ; https://en.wikipedia.org/wiki/Factorial (lambda (n) "factorial of integer n, computed recursively as per mathematical induction and algorithmic recursion" (if (= n 0) 1 (* ; multiplication function n ; n of our mathematical induction expression (! ( n 1)) ; !(n 1) via the magic of a recursive call which ; terminates when n=0 );* ) ) ;lambda ) (insert "\n\n;;; Results ==> " (prin1tostring (mapcar ; is a higherorder function which allows us to ; use the following function as a catspaw '! ; we'll map factorial onto a list of integers ranging from ... (numbersequence 0 6) ; 0 and 6, inclusive ))) ;;; Results ==> (1 1 2 6 24 120 720) 
8thNovember2017, 11:03 AM  #29 
Member
Join Date: Jun 2017
Posts: 650

Re: The Coding Thread
For a perhaps slightly more challenging recursive formula, how about computing the square root of 2 as a continued fraction?

8thNovember2017, 06:30 PM  #30  
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Quote:
Here's a lisp function to help math weenies via domainspecific language which panders to their standard symbol `k' to mean `integer': Code:
; emacs lisp ; note that predicates resulting in truefalse answers typically end with ; `p' via the lisps proper as contrasted with scheme dialects of the lisps, ; whereas scheme notation uses the `?' suffix, thus `integer?' as a ; transliteration of the `integerp' of the lisps proper (defun k? (n) "Is k a member of `integer'?" ; (numberp n) ;< We'd use this to test if any kind of number (integerp n) ) ; test k? from 1 to 2 by 0.5 increments (insert "\n;;; results ==>\t"(pptostring (mapcar (lambda (n) (cons n (k? n))) (numbersequence 1 2 0.5))) "note that 2.0 to the lisp REPL is a `real' rather than an integer") ;;; results ==> ((1 . t) (1.5) (2.0)) Code:
; ref: http://sicp.ai.mit.edu/Fall2004/manuals/scheme7.5.5/doc/scheme_5.html#SEC43 ; Scheme code goes here, ya lazy bastards! ; ; hint: one can develop such code via: http://tryscheme.sourceforge.net/ ; along with javaScript if one is so inclined. ; ; If no participant in this thread expresses an overt interest I'm not going to waste my time in the hope that oneormore lurkers will benefit by it in some way. Frankly these mathy numerical examples bore the ass off me. If I'm using emacs lisp to `code' there is more sexy  to me  stuff I could be demonstrating than dorky numerical methods requiring or entailing mathematical induction. 

8thNovember2017, 06:53 PM  #31  
Member
Join Date: Jun 2017
Posts: 650

Re: The Coding Thread
Quote:
Here is a recursive implementation of the squareroot of 2 thing in R: Code:
sqrt2 < function(maxdepth = 10){ f < function(depth){ if(depth == maxdepth) 2 else 2 + 1 / f(depth + 1) } 1 + 1 / f(1) } 

10thNovember2017, 04:54 AM  #32  
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Quote:
And therein lies the rub. None of us can anticipate the necessarilysubjective `interest' experienced by each of the participants and lurkers alike. You seem to prefer numerical computing & mathematical induction for proofs. @Animekitty listed things she doesn't know much about  I believe indicating that she's curious  as well as presenting code supportive of her interest in modeling neural nets, brains. @Turnevies used matlab to do the fig sequence, but didn't reveal interest outside that problem @Cognisant gave the fib sequence a try but also didn't reveal interest. There've been close to 700 views, but that a `view' has been registered doesn't provide any feedback on WHAT  if anything  the viewer found interesting, useful, practical ... whatever. However I am AWARE of what I find interesting, useful, or such from my perspective ... as well as having encountered `interest' expressed in oneormore other threads. So I'll proceed from this point of departure. Code:
; launch a new tab visiting this thread via the emacs user's default web browser (browseurl "https://intpforum.com/showpost.php?p=578983") Code:
; launch a new tab visiting this specific post via the emacs user's default web browser (browseurl "https://intpforum.com/showpost.php?p=579726&postcount=32") 

10thNovember2017, 01:40 PM  #33 
Member
Join Date: Jun 2017
Posts: 650

Re: The Coding Thread
For something slightly more involved: a program that downloads a thread from this forum and extracts the posts in pure text form. Later on we can perhaps analyze the text itself; say, various stats like the average post length of various users, their vocabulary etc.

10thNovember2017, 07:41 PM  #34  
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Quote:
Rather than from a threaddownwardtopost progression it might be easier in some languages to build a system which can parse a post  bbcode tags, text, code blocks and such  and allow one to represent and save the parsed stillstructured data in oneormore data structures, file formats, or such. As many apps use CSV and/or TSV to import and export data I imagine that whatever we come up with that uses these singlecharacter delimited formats will be of more use to noncoders and coders alike. Any metacoding thoughts on this? As this is a generic coding thread we'd want implementations of whatever specifications emerge via several programming languages. I'm willing to demo code in emacs lisp; I'll leave the brainfuck implementation to others. So ... I'm imaging voluntacracy producing code snippets available for use in topdownard, bottomupward, and middleoutward design strategies in multiple programming languages available for use as jigsaw puzzle pieces available for application and reuse; I'm thinking that a towerofbabel combinatatorial explosion can manifest. This might be a case where a languageneutral block diagram might be of use. Not that I'm volunteering to either initiate or contribute to one, mind you. 

11thNovember2017, 10:14 PM  #35 
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Code:
;;; Here's one for those with easy access to one of the emacsen (w3m "https://intpforum.com/showthread.php?p=579756#post579756") ;note that there a many ways of accessing web pages, URLs and such. ; w3m is one function which happened to do a pretty good job in this case. ; eww may give better results for other pages (eww "download emacs") ; As two different functions were used to access web `content' a separate buffer is used for each (listbuffers) Code:
; * org * * Here's one for those with easy access to one of the emacsen ** [[elisp:(w3m "https://intpforum.com/showthread.php?p=579756#post579756")][view this thread via emacs and w3m]] note that there a many ways of accessing web pages, URLs and such. w3m is one function which happened to do a pretty good job in this case. ** eww may give better results for other pages [[elisp:(eww "download emacs")][use Emacs Web Wowser to launch a duckduckgo search for `download emacs']] ** [[elisp:(listbuffers)][As two different functions were used to access web `content' a separate buffer is used for each]] 
12thNovember2017, 07:39 PM  #36  
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Quote:
Scala was designed as an improvement upon Java by adding functional features. Clojure allows one to (re)use Java jar files while exploiting Lisp functionality, multiprocessing, etc. And it's not an eitheror situation anyway, as one may use OOP and functional programming together. In the world of emacs in which I play every day one can use EIEIO and CEDET SLIB  what clib is to C, though in the world of Scheme  contains libraries for a couple of different ways of implementing Objects. Quote:
For instance, from a math lover's perspective in a time when computer cycles are dirt cheap and a programmers time is not, how `efficient' seems it to require the C programmer to HAVE TO perform type casting of wouldbe `numbers' which aren't onetoone and onto with a mathematician's notion of integers, reals, and complex numbers ... rather than exploit the numerical tower of Scheme? Quote:
Scheme, Common Lisp, and Logo ALL support iteration as well as recursion. So if one wanted to compare iteration with recursion one could and CAN perform such experiments. Moreover, because Scheme can be translated into C and C can be compiled to assembly language which in turn can be assembled into machine code, one can perform experiments on execution speed, resource usage, and such as metrics of `efficiency'. Plus  nowadays  C and Scheme can be mixed in the same source code via GUILE; so one can obtain the best features of both. {note: C's macros suck; The hygienic macros of Scheme do not.} As someone who has resorted to mathematical induction it would seem that you'd be in favor of the use of recursion to manifest/implement induction within the domain of coding rather than to `factor' it out to some nottightlyintegrated sideline process. To revisit "which I imagine would be quite slow for, say, the Fibonacci problem above." you might be interested to know that the Scheme specification REQUIRES that for an implementation of Scheme to `be' or `qualify as' such it MUST support tail recursion, which `is' or `can be' implemented as a goto at the machine language level. So, pending experimentation, you might want to rethink your asyetgrounded suspicion that recursion necessarily either `is' or `substantially is' slower or lessefficient than iteration ... especially when you as a coder prefer mathematical induction which can be performed via recursion. 

1stDecember2017, 08:09 PM  #37 
Member
Join Date: Jun 2017
Posts: 650

Re: The Coding Thread
R code I used to download threads. "read_multiple_threads" is the main function.
Spoiler:

14thDecember2017, 07:14 AM  #38  
INTP 5w4 Iconoclast
Join Date: Mar 2010
Location: Upstate NY, USA, Earth
Posts: 167

Re: The Coding Thread
Quote:
I've been wrestling with recovering from a WinBlows virus, reinstallation, creation of a Multiboot USB pendrive, Linux Mint, trying to post to this group to no avail until receiving a clue from Jennywocky ... experimenting with embedding R source code in an orgmode file. So as to not hold up possible progress by others I'll provide a template of sorts for use by whoever has Emacs and R available. The following `code' can be inserted into a file, opened in emacs to have it interpreted as an Org outline which Supposedly allows the embedded R code to be executed. Spoiler:
I've got some experimenting of my own to do in getting this feature to work on my system. Have to have the R executable in a directory somewhere and establish a link to within emacs. Once a!gain, thanks for the R code! 

Thread Tools  Search this Thread 
Display Modes  

