<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gabriel Borges on Medium]]></title>
        <description><![CDATA[Stories by Gabriel Borges on Medium]]></description>
        <link>https://medium.com/@gabrielfr.borges?source=rss-bb290f48c1c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JpPPLTn-wnhmkavGCpZaWg.png</url>
            <title>Stories by Gabriel Borges on Medium</title>
            <link>https://medium.com/@gabrielfr.borges?source=rss-bb290f48c1c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:25:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gabrielfr.borges/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Sobre o crime de seduzir com más intenções]]></title>
            <link>https://medium.com/@gabrielfr.borges/sobre-o-crime-de-seduzir-com-m%C3%A1s-inten%C3%A7%C3%B5es-b03487aadf38?source=rss-bb290f48c1c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b03487aadf38</guid>
            <category><![CDATA[poema]]></category>
            <dc:creator><![CDATA[Gabriel Borges]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 15:24:27 GMT</pubDate>
            <atom:updated>2024-09-26T15:24:27.883Z</atom:updated>
            <content:encoded><![CDATA[<p>Minha musa desenha</p><p>Uma estrela no céu</p><p>Que ilumina</p><p>Meu mausoléu​</p><p>…​</p><p>Aquela que me ilumina</p><p>Faz-me de réu</p><p>Sem planejar minha ruína</p><p>Acende minha alma num fogaréu</p><p>…</p><p>Seu fogo me encanta</p><p>E sua fumaça</p><p>Me conta sua trama</p><p>…</p><p>Ela me abraça</p><p>Diz que ama</p><p>Ressuscitar para a desgraça</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b03487aadf38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crítica aos crimes ambientes em poema]]></title>
            <link>https://medium.com/@gabrielfr.borges/cr%C3%ADtica-aos-crimes-ambientes-em-poema-686016a93343?source=rss-bb290f48c1c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/686016a93343</guid>
            <dc:creator><![CDATA[Gabriel Borges]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 15:19:05 GMT</pubDate>
            <atom:updated>2024-09-27T21:11:06.232Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crítica aos crimes ambientais em poema</h3><p>A Beleza cinza que sobrevoa os céus agora castiga<br>Não por vingança,<br>Mas por justiça.<br> <br>Pelo choro da mais nova vida,<br>Pela chacina<br>É por tudo isso que<br>O império urbano agora<br>Declina<br>…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=686016a93343" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Poema papéis trocados]]></title>
            <link>https://medium.com/@gabrielfr.borges/poema-pap%C3%A9is-trocados-e1db19d1fc8f?source=rss-bb290f48c1c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1db19d1fc8f</guid>
            <category><![CDATA[poema]]></category>
            <dc:creator><![CDATA[Gabriel Borges]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 15:17:40 GMT</pubDate>
            <atom:updated>2024-09-26T15:17:40.002Z</atom:updated>
            <content:encoded><![CDATA[<h3>Gabriel Borges</h3><p>A Prosa se fez de poema,<br>mas não tinha métrica nem rima.</p><p>A carta do remetente <br>que se confundiu com um destinatário<br>nunca foi escrita.</p><p>O protagonista resolveu interpretar<br>um espectador descontente com o show.<br>A criatura, perdida,<br>pensou ser seu próprio criador.</p><p>O barco decidiu ser uma onda e se afogou.<br>Alguém viu ninguém no espelho e resolveu se matar.</p><p><em>Papéis Trocados</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1db19d1fc8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quiprocó]]></title>
            <link>https://medium.com/@gabrielfr.borges/quiproc%C3%B3-4b2928ee2437?source=rss-bb290f48c1c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b2928ee2437</guid>
            <category><![CDATA[crônicas]]></category>
            <dc:creator><![CDATA[Gabriel Borges]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 12:00:03 GMT</pubDate>
            <atom:updated>2024-09-24T12:00:03.897Z</atom:updated>
            <content:encoded><![CDATA[<p>Dois amantes, bem discretos, fazem seus sórdidos encontros no silêncio interminável de uma biblioteca. Em meio a imensa solidão, entre as estantes, que escondem o amor mais puro do mundo.</p><p>Lá deleitavam um do outro, ele recita poemas recheados de amor e tristeza dos seus autores, lia histórias de tragédia e humores até perder a voz. Ela lhe emprestava a atenção e lhe afagava o corpo com os cuidados de sua mão tão delicada.</p><p>Quando de repente as luzes se apagam e ela repentinamente vai embora, já que ele não lhe é mais útil. O que lhe resta é, como um livro empoeirado na estante que é, esperar alguém chegar e ir embora de novo.</p><blockquote><strong>Quiprocó </strong>(verbete)</blockquote><blockquote>Engano, erro que consiste em tomar-se uma coisa por outra.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b2928ee2437" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frustação e medo]]></title>
            <link>https://medium.com/@gabrielfr.borges/frusta%C3%A7%C3%A3o-e-medo-a97ad06f1b5a?source=rss-bb290f48c1c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a97ad06f1b5a</guid>
            <category><![CDATA[crônicas]]></category>
            <dc:creator><![CDATA[Gabriel Borges]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 11:58:18 GMT</pubDate>
            <atom:updated>2024-09-24T11:58:18.674Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Escrevi isso quando estava muito angustiado. Hoje tudo se resolveu, mas a dor que sentia no momento foi, eu acredito, bem representado. Se você se identifica com este texto, procure a Cristo, ele irá te resgatar assim como me resgatou.</blockquote><p>Dias frustrados me molham na chuva, sinto o gosto da angustia por toda minha boca. Escondo minhas decepções para que eu ainda pareça aquilo que as pessoas acham que eu sou. Minha alegria é um sapato molhado que da a falsa sensação de estar num andando no leito de mar. Sinto que se eu fechasse meus olhos por um momento apenas veria o por do sol engolir todos meus efêmeros anseios.</p><p>Mas quando os últimos raios de sol me esquentam meu peito, quando a brisa do mar me e congela até os ossos. Percebo que tudo aquilo é uma ilusão, estou na sarjeta de um beco escuro com os pés molhados, cansado depois de me procurar a vida inteira. E agora perdido, me acho uma mera ilusão. Sou exatamente aquilo sempre tentei não descobrir, não sou nem nunca passei de um garoto assustado.</p><p>Fugindo de mim mesmo, me perco daquilo que era e me acho em transgressões que ofendem a única coisa que ainda acredito. Num misto de angustia, culpa e ódio por ser tão fraco me descubro de novo em uma palavra: patético. É o que mais sinceramente me descreve, porque a insatisfação do meu estado atual me faz querer mudar, mas o medo, que é muito maior, me faz apreciar meu sofrimento.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a97ad06f1b5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A menina que vendia fósforos]]></title>
            <link>https://medium.com/@gabrielfr.borges/a-menina-que-vendia-f%C3%B3sforos-7ac2e1c3a4a8?source=rss-bb290f48c1c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ac2e1c3a4a8</guid>
            <category><![CDATA[crônicas]]></category>
            <dc:creator><![CDATA[Gabriel Borges]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 11:51:50 GMT</pubDate>
            <atom:updated>2024-09-24T11:51:50.257Z</atom:updated>
            <content:encoded><![CDATA[<p>Na noite mais fria do inverno mais rigoroso que já existiu, uma pequenina garota vendia a última coisa que lhe restou, fósforos. Passou manhã e tarde inteira dos últimos quatro dias tentando vender os seus últimos 3 fósforos, mas ninguém comprara,já que esperavam por uma aconchegante lareira em casa para expulsar o inverno tão tenebroso.</p><p>Isso foi quando no final da tarde, o velho livreiro itinerante parou de cantar e a ouviu no momento em que a garota o chamou, já sem esperança aparente, disse “Por favor, ó sábio livreiro, vendo meus últimos fósforos, é tudo que tenho e sem dinheiro vou morrer de fome esta noite”. Ele parou e respondeu “Que triste história, mas onde estão seus pais? Não deveriam eles cuidar para que fique segura?”.</p><p>A menina respondeu com lágrimas no peito:</p><p>- Eles se foram, a nevasca os levou junto com minha casa e tudo que tinha.</p><p>Com muita dó da garota ele decidiu lhe dar o que tinha de mais valor:</p><p>- Pobre criança, não sabe que ninguém aqui, nem o rei, teria dinhero para comprar um de seus fósforos? Eles são tudo que tem e quer vender para quaquer um que tivesse dinheiro para comprar? E mesmo que lhe comprasse depois que comesse não teria mais nada novamente e morreria. Fica com o que tem e terminará a vida feliz.</p><p>Assim sem mesmo se despedir foi o livreiro embora. E a pequena menina sem entender uma palavra que ele disse agradece, pois todos sabiam que faltar com respeito com um livreiro era sinal de má sorte. Dali ela voltou para o beco que dormia nos últimos dias para passar, o que já sabia ser, sua última noite.</p><p>Para afastar o frio ela decidiu riscar um fósforo para talvez trazer a memória o conforto de sua casa. E quando o fogo surgiu na frente dos seus olhos no calar da noite o frio e toda fome foi embora, ela estava sentada de novo na mesa da sua casa junto a lareira para o jantar de ação de graças. Mas o gélido e cruel vento levou tudo embora e lá estava ela com fome, frio e aos prantos naquela cruel noite de inverno.</p><p>Foi quando decidiu riscar mais um fósforo o protegendo com a outra mão para que não lhe a noite não o roubasse novamente. E desta vez o fogo era mil vezes mais forte, por que já não estava sozinha, mas seus pais estavam junto com ela, o chão que era sujo e hostil era agora a confortável cama dos seus amados pais e eles a guardavam junto se seus braços e ela sabia que nada poderia lhe acontecer, porque ali era o lugar mais seguro do mundo.</p><p>Quando se percebeu no desagradável beco, com fome, frio, tão só que até as lágrimas lhe fugiram e com com as pontas dos dedos doloridas, não pelas pequenas chamas do fósforo, mas pelas memórias que escapavam pelos os dedos e se encontravam no último fósforo. A última chance de escapar daquele pesadelo para os braços de sua mãe, o colo de seu pai, para o jantar de ação de graças, para um lugar melhor.</p><p>Para este último fósforo, ela decidiu lembrar do que tinha de mais valioso. Já não era mais aquele fósforo, era a esperança que tinha que tudo ia dar certo quando seu pai o falava, ele nunca mentia e foi isso que ele disse por último, então foi isso que fez. Acendeu o último fósforo e lá estava ela segura pela promessa do seu pai, em um beco escuro e ameaçador, dormindo no chão ingrato e com fome novamente. E foi assim cansada de tudo aquilo que dormiu, e como já tinha sonhado todos os seus sonhos e vivido o pior de seus pesadelos ela simplesmente descansou os olhos até ser acordada por uma canção amiga.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ac2e1c3a4a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Devaneio de um momene]]></title>
            <link>https://medium.com/@gabrielfr.borges/devaneio-de-um-momene-0099d51bdf52?source=rss-bb290f48c1c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0099d51bdf52</guid>
            <dc:creator><![CDATA[Gabriel Borges]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 11:45:27 GMT</pubDate>
            <atom:updated>2024-09-24T13:47:04.233Z</atom:updated>
            <content:encoded><![CDATA[<h3>Devaneio de um breve momento</h3><p>O vento desfaz cada grão que um dia já fui feito, cada vez mais perto da morte, meu corpo se desfaz periodicamente. Com esse tempo conto minha ruína, conto cada segundo, cada minuto, mais perto do último.</p><p>Em cada segundo nasço e morro eternamente, sem cessar mato meu eu por um próximo, sabendo que nunca mais vou ser o mesmo de novo. Assassino o presente por um futuro incerto, que nunca vou conhecer.</p><p>Lá se vai mais uma vida eterna de imensa complexidade e formosura, ímpar diante cada outra. Sujeita ao esquecimento, ela morre para dar início a um segundo novo. Talvez seja pelo fato de não ser eterna que me faça desejá la tanto assim, talvez seja só mais uma cobiça carnal, ou talvez não seja nada. Só mais um devaneio de outro velho momento com medo de morrer e ,acima de tudo, de assumir que tem medo. Outro velho momento que não compreende o fim e se corrompe esquecendo do seu primeiro objetivo, a morte.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0099d51bdf52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[O bosque, seu senhor e sua primavera]]></title>
            <link>https://medium.com/@gabrielfr.borges/o-bosque-seu-senhor-e-sua-primavera-00685a4fc0a4?source=rss-bb290f48c1c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/00685a4fc0a4</guid>
            <category><![CDATA[crônicas]]></category>
            <dc:creator><![CDATA[Gabriel Borges]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 11:40:04 GMT</pubDate>
            <atom:updated>2024-09-24T11:40:04.101Z</atom:updated>
            <content:encoded><![CDATA[<p>A lua e o sol me disseram que não voltariam amanhã, pois teu sorriso seria como luz para os bosque de amores cujo eu sou o senhor. Por isso mandei as árvores que não deixassem cair uma folha em teu caminho, nem que escondessem seus frutos de ti, as flores que te fizessem uma belíssima coroa.</p><p>Ordenei aos pássaros que cantassem de dia e de noite suas mais belas canções, a todos os animais que habitam em minha terra foi ordenado que exilassem do chão todo e qualquer objeto que poderia machucar seus pés, lutei mais uma vez com os lobos e animais perigosos não cheguem perto de ti.</p><p>Pedi a brisa que te acolhesse com carinho e carregasse seu perfume até mim, aos ecos que repetissem somente sua encantadora voz, a queda d’água e ao riacho para trazer desde sua fonte toda espécie de boa sorte e por último ao tardar da noite as estrelas me pediram para chegar mais perto para ver com nitidez sua formosura.</p><p>Logo pela manhã chega alegre e saltitante. Os longos cabelos negros, o sorriso inocente e despreocupado, as vestes vermelhas, a boca delicada que entoa os cantos da floresta, os olhos escuros para tomar o coração de todo aquele que o olhar cruzar com o seu. Assim é a dama que traz para minhas terras de paixões a primavera, suspiros de amor e olhares de desejos.</p><p>A orla do teu vestido faz desabrochar a beleza das flores, a gentileza da sua mão traz vida a tudo que toca, os teus pés fazem as trilhas sem rumo dos animais que te seguem para ver te de perto. Os pássaros não resistiram a sua boca cheias alegria e esqueceram de cantar, as flores desabrocham e correriam se pudessem para ver o teu doce encanto.</p><p>Logo os teus caminhos cruzam com os meus e eu, humilhado com o presente de seus encantos te ofereço meus humildes abraços para te receber.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00685a4fc0a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Try With Functional Programming (Knapsack Problem)]]></title>
            <link>https://medium.com/@gabrielfr.borges/my-first-try-with-functional-programming-knapsack-problem-f92cd4c0ff13?source=rss-bb290f48c1c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f92cd4c0ff13</guid>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clojure]]></category>
            <category><![CDATA[trying-new-things]]></category>
            <dc:creator><![CDATA[Gabriel Borges]]></dc:creator>
            <pubDate>Sat, 10 Jul 2021 18:24:56 GMT</pubDate>
            <atom:updated>2021-07-10T18:24:56.944Z</atom:updated>
            <content:encoded><![CDATA[<h3>My first try with Functional Programming (Knapsack problem)</h3><p>I have been reading about functional programming(FP) for a while now. But yesterday I decided to write something slightly difficult so i could exercise the thinking in different paradigm. So here is my story in first real try with FP.</p><blockquote>Note #1: This is not a tutorial or introduction to FP.</blockquote><blockquote>Note: #2: I am not an expert, on the contrary, just a guy trying a different thing.</blockquote><h3><strong>The Language</strong></h3><p>First thing was to choose a FP language there is some great options like Elixir, Haskell or Clojure. I choose the latter because of great <a href="https://clojuredocs.org/">docs</a>, the integration with the JVM (which is a interesting subject to study in the future) and a talk of Rich Hickey (creator of Clojure) in immutability.</p><p>I started studying FP because of parallelization and concurrency (running two pieces of code in the same time or almost), but when I watched “<a href="https://www.youtube.com/watch?v=-6BsiVyC1kM">The Value of Values</a>”, immutability intrigued me a lot more than improvement in performance with parallelization.</p><p>Clojure is a lisp so we are going to a have a lot of parenthesis from now on</p><pre>;; this is a comment in clojure<br>;; all clojure operations are prefix<br>;; the operator always comes first and then the operands<br>;; a operation is always wrapped in parens<br>;; i will comment the outputs with =&gt;</pre><pre>(+ 1 2)<br>;; =&gt; 3<br>;; weird, ham?</pre><pre>(concat [0 1] [2, 3])<br>;; =&gt; [0 1 2 3]<br>;; arrays are defined with the symbol &quot;[]&quot;<br>;; they are separeted with spaces (commas are optional)</pre><pre>(defn hello [name] (str &quot;hello, &quot; name))<br>;; this is a function called hello<br>;; hello has one argument called name</pre><pre>(hello &quot;reader&quot;)<br>;; =&gt; &quot;hello, reader&quot;<br>;; this is how hello function is called</pre><pre>(-&gt;&gt; 1<br>  (+ 2)<br>  (+ 3)<br>  (- 10))<br>;; =&gt;4<br>;; &quot;-&gt;&gt;&quot; is the thread operator<br>;; it takes the first result and passes to next func. as last arg<br>;; same as (- 10 (+ 3 (+ 2 1)))</pre><h3><strong>Immutability</strong></h3><p>How could you write complex program without variables and it be easier to understand? This could seem far fetched, but i believe its true. As Rich says data is a fact and facts are immutable. If a sack has 3 items at a given time this can not be changed, items can be added or removed, but the fact the bag in that time had 3 items cannot change.</p><h3>Functions</h3><p>If functions are so important in FP that they name the paradigm, what is a function ?</p><p>FP functions have a very specific definition: Pure functions or mathematical function, in other words deterministic (the same parameters always produces the same output), functions should not have side effects and functions can be parameters of other functions (for now this is all that we have to now).</p><h3>The Problem</h3><p>I choose the classic knapsack problem used to demonstrate dynamic programming. It consist of calculating the best items T to go in a bag of size N (I will explain better ). I choose this problem because it is natural to solve in a imperative style, so it would be interesting to try in a different style.</p><p>The following image shows a representation of a sack of size 6 and three items of size 4, 3, 3 and values 10, 6, 5. As items #2 and #3 together have more value than #1 the sack is filled with value #2 and #3 and has value 11.</p><figure><img alt="Illustration of knapsack with the best items" src="https://cdn-images-1.medium.com/max/719/1*NW_A4M66YzaIgCzvRoWUiw.png" /></figure><p>The dynamic approach is a matrix that with lines for each item (plus one for a empty sack) and columns for each unit of the size of sack. Each cell has the best value for a sack of size “column” using the items “line” and above</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*ifDam-0tOL9NT2XXHSNxwQ.png" /></figure><p>The matrix is filled iterating in through cells with the following algorithm</p><pre>if current item fits this sack then<br>    return max(previous best, current item + remaining items)<br>else<br>    return previous best<br>endif</pre><h3>The Solution</h3><blockquote>Note #1: I used some clojure standard functions, using <a href="https://clojuredocs.org/">clojuredocs</a> to find utility functions and examples is a great idea</blockquote><blockquote>Note #2: For the sake of simplicity I did not include all tests</blockquote><p>We are ready to start solving our first slightly difficult problem using FP.</p><p>I used Leiningen to make a module. To use it download and run lein new learn to create a new module</p><p>First I started by writing a test so I was not running blind during my clojure exploration. Tests are made with deftest , testing functions and is as assertion. To test run lein test</p><pre>(deftest example<br>  (testing &quot;message&quot;<br>    (is (= 1 1)))</pre><p>The code below is a a basic test for the knapsack problem. {:w 4, :v 10} is a hash map representing a item of size(or weight) 4 and value of 10. let is used to declare local variables, (let [sack 10] (is (= sack 10))) asserts the local variable sack is 10. last gets the last value in a sequence (any ordered list or array like structure).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e500952852587734f89561a9e1c02f2/href">https://medium.com/media/8e500952852587734f89561a9e1c02f2/href</a></iframe><p>I implement the solution incrementally to get familiar with Clojure. First I will loop in items and return a list of empty lists of size sack +1.</p><h3>Solution #00</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc80482a2517a4e04cf7a1f9d7b415f8/href">https://medium.com/media/dc80482a2517a4e04cf7a1f9d7b415f8/href</a></iframe><p>Lots of new things, in loop the initial values of prev-item and items is declared, prev-item as repeat n+1 &#39;() , which returns a repeat list of n + 1 empty lists, the &#39; tells clojure that () is a list literal, not a function call. loop also has a body with if and recur , the latter recalls loop with the new values of prev-item(the same as initialized) and items skipping the first value.</p><pre>;; example<br>(loop [i 0] (print i &quot; &quot;) (recur (inc i))<br>;; prints 0  1  2  3... infinite</pre><p>The if inside loop receives a testand two values, if test is evaluated to true, then the <em>first</em> argument is evaluated and returned, if test is evaluated to false, then the <em>second</em> argument is called.</p><p>With that recursion and stop conditions are made. For every item in items prev-items is passed to the loop again, in the end the initial value of prev-item returned.</p><pre>;; example<br>(knapsack 3 [{:w 2, :v 1}])<br>;;=&gt;(() () () ())</pre><h3>Solution #01</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4eec1cf150d67050f5e965290f97b7b6/href">https://medium.com/media/4eec1cf150d67050f5e965290f97b7b6/href</a></iframe><blockquote>defn- defines a private function</blockquote><p>More things to understand, now instead of passing the initial value of prev-item, the current item is inserted in the sack if it fits.</p><p>fit-sack? receives size of sack n and item . get returns the value of key :w (the size of the item) and compares to n .</p><p>best-knapsack-of-size receives sack the previous sack, the size n (column of the matrix) and the current item . If the current item fits the sack, returns the current item in a list, if not, returns the previous sack of the same size n.</p><p>best-knapsack ranges from 0 to the size of the previous sack calculating the best items for a sack of that size. #() is a lambda function. In best-knapsack , the lambda calls best-knapsack-of-size passing the argument % received in the lambda function.</p><p>This solution returns the last line of the matrix with the last item passed to knapsack inserted in each column it fits. For example</p><pre>;; example<br>(knapsack 3 [{:w 2, :v 1}])<br>;;=&gt; (() () ({:w 2, :v 1}) ({:w 2, :v 1}))</pre><h3>Final Solution</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0d738213a840102103141cb7be9a4ee/href">https://medium.com/media/b0d738213a840102103141cb7be9a4ee/href</a></iframe><p>This is my final solution to the knapsack problem, I implemented the last step of the algorithm mentioned above and added some array conversion to access values in constant time.</p><p>best-knapsack-of-size now inserts the previous items or the current item + the items of the last sack that fits the remaining space. The -&gt;&gt;(theard last) operator as explained before, passes the output as the last argument of the next call (similar to pipe in linux) and returns the result.</p><p>fill-extra-items is the function responsible for finding the items of the last sack that fill the remaining space of current sack already with the current item. (get arr i) returns the value at i of the array arr.</p><p>choose-best receives the previous items, the current items + extra and returns the option with best value. To choose the best option, sum-items-value is used as key.</p><p>sum-items-value sums the values of key :v in the array of items.</p><h3>Conclusion</h3><p>I had never tried something similar to the lisp style of Clojure, using emacs cider helped a lot. Features as rainbow parens, shortcuts to move, add parens and more is cool things to have while trying this language. The source code is very readable once you know the basic structure of a function.</p><p>The exercise of thinking in a functional paradigm and describing in a article was very productive. Although I started studying FP because of parallelization, immutability is my main topic of interest in this subject, in the beginning things can be confusing, but once you get used to the principals of FP, things start to get easier(debugging inclusive).</p><p>Next I would like to explore Clojure type hints, macros and Java interaction. Or maybe an article about FP fundamentals similar to “<a href="https://www.youtube.com/watch?v=VUhlNx_-wYk">Programming with nothing</a>”.</p><p>As I said in the beginning I am not a expert, if you have any critique, additions or suggestions please comment bellow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f92cd4c0ff13" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>