<?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 Jaya on Medium]]></title>
        <description><![CDATA[Stories by Jaya on Medium]]></description>
        <link>https://medium.com/@kasa288?source=rss-afac825c346b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-WEbBzFhfq4GTEGk.jpeg</url>
            <title>Stories by Jaya on Medium</title>
            <link>https://medium.com/@kasa288?source=rss-afac825c346b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 02:23:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kasa288/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[Functional Patterns Part 1]]></title>
            <link>https://medium.com/@kasa288/functional-design-patterns-part-1-9be81d843900?source=rss-afac825c346b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9be81d843900</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Jaya]]></dc:creator>
            <pubDate>Sun, 28 May 2017 03:45:43 GMT</pubDate>
            <atom:updated>2017-05-29T21:17:06.025Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s that time of the week. I finally have some free time to produce some content. Before I get started, shout out to all the people who started following, liking and recommending my stuff. You guys are the best! I’m glad I could share some knowledge with you guys and I hope I made you a little smarter!</p><p>Back to business.</p><p>If you are a coder, you have definitely heard of design patterns. If you have not, you might be a beginner, so no worries. If you’re not, don’t freak out, I got you. I’m gonna do an article on OOP patterns as well at some point, so be on the lookout for that. Design Patterns are extremely important. They let you write some really good, clean and reusable code. now, they are very different from design principals. <strong>DO NOT GET THE TWO MIXED UP. </strong>People like to ask the difference between the two during interviews and getting this wrong is a surefire way to get rejected.</p><h4>Design Pattern</h4><p>A design pattern is a general repeatable solution to a commonly occurring problem. The purpose of a design pattern is to leverage the wealth of knowledge of developers who came before you in order to solve old problems that you may encounter easily. It also makes communicating problems and solutions very easy. For example: creational, structural, or behavioral patterns.</p><h4>Design Principal</h4><p>A design principal is an established idea or best practice that facilitates the software design process. They are not language specific, so you can use them anywhere. For example: encapsulation, creating JavaBeans, is-a vs has-a relationships, object composition, etc.</p><p>I wouldn’t say memorize this word for word, but make sure you know the difference between the two and examples of each.</p><blockquote>Seriously, getting this wrong is a rookie mistake.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*FB5Cn-zL-X5ouSOxjNXHSg.png" /><figcaption>Don’t get this wrong</figcaption></figure><p>Anyways, without further ado, you’re previously scheduled programming will commence.</p><h3>Tail Recursion</h3><blockquote>Tail recursion lets you repeat computations without using mutable state and without overflowing the stack.</blockquote><p>This patterns is used to replace iteration. <strong>Iteration is an imperative technique that requires a mutable state which goes against the FP principal of immutability</strong>. Recursion lets you iterate without immutability. But, recursion creates a new frame on the program call stack on each call. In other words, our solution takes memory proportional in size of the sequence you’re operating on (i.e Memory of O(n)). It would be insane to iterate over a million items using recursion.</p><p>We can get around this using tail recursion, which is <strong>optimized to use a single frame on the stack</strong>. This process is called <em>tail call optimization</em> or <em>TCO</em>.</p><p>As with any recursive method, you need a <em>base case </em>and <em>recursive case. </em>The base case pertains to what happens when you reach the terminal case of a recursive operation. Next is the recursive case, and this is where things get a little hairy.</p><p>The reason we have a stack that grows with each recursive call is because we need the result of the recursive call to finish the overall computation. This means that the runtime has to store intermediate values on the stack. But, if we can eliminate these intermediate values and make sure that the recursive call is the last thing that happens, we can eliminate this problem. All you have to do is pass the intermediate values in the recursive call. This takes advantage of TCO.</p><p>You can write programs like this in Java, but the JVM does not support TCO directly. Scala optimizes tail recursive calls at compile time so you get the same bytecode as iteration. You have to make sure to use the @tailrec annotation.</p><p>The structure usually goes as follows (I will try to be language agnostic):<br>methodName(input, accumulator){<br>base case: ….<br>recursive case: methodName(input, accumulator)<br>}</p><h4>Example Usage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*ugUxN2chVDEYDFxmTXUiBw.jpeg" /><figcaption>An example of a tail recursive method</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*nJLXxknRyEs-HRWhQ0xEsQ.jpeg" /><figcaption>Output for example code</figcaption></figure><p>As you can see, we used tail recursion to combine values from two lists and create objects from them.</p><blockquote>Why would I use this when I can still use iteration?</blockquote><p>Tail recursion eliminates a source of mutability. You no longer have an extra index variable. Your code explicitly states what data structures are being operated on and generated because they are both passed as parameters. Also, there are a lot of library functions available that can help you save time by shortening your code. For example: the above code can be shortened into a single line by doing the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*7Y56xdaDimjJTwYLeODZKA.jpeg" /></figure><h3>Mutual/Indirect Recursion</h3><p>This is really useful for some complex algorithms. Tail Recursion is considered to be self-recursive, which is great for solving some problems. But, when you get to traversing tree-like structures, you need something more complex.</p><blockquote>In mutual recursion, instead of making the calls directly, we return a function that would make the desired call. The rest is up to the compiler or runtime. This is called a trampoline.</blockquote><p>Scala hides a lot of details of this process and gives us two methods: <strong>tailcall() </strong>to make the mutually recursive calls and <strong>done()</strong> to call when we’re done with recursion.</p><p>Let’s look at a simple example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*lVJES9sLRf6IMHEuMAF_iA.jpeg" /><figcaption>Simple example</figcaption></figure><p>This seems to make sense. You have two methods that call each other to back and forth to solve a problem. Sure, there are better options, but just bear with me here. Everything seems to work fine, until you get to a really large number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*DTomcJKdqo0mDlSGKo0wQw.jpeg" /><figcaption>Output for code sample</figcaption></figure><p>When we got to a large number, we got a stack overflow exception. Don’t worry, we can fix this with trampolining.</p><p>Before we get to the code sample, lets check out what tools are available to us: tailcall(), done() and result().</p><p><strong>tailcall()</strong>: makes the recursive call<br><strong>done()</strong>: returns final result from recursive calls in a TailRec object<br><strong>result()</strong>: returns the value stored in TailRec object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*daDZLk5M12R05VS-A01EUw.jpeg" /><figcaption>Mutual Recursion done right</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*fouH-BNx1ujg69pwy21LrQ.jpeg" /><figcaption>Output</figcaption></figure><p>This time it runs without throwing an exception, which is great.</p><p>This technique is great when working with State machines, which is an important component in the actor model(i.e. Akka). If you have time, try to use this pattern to model state changes in chemistry(i.e. Solid, Liquid, Gas, etc.).</p><h3>Filter-Map-Reduce and Chaining Operations</h3><p>This one should be familiar to a lot of you.</p><blockquote>You will be chaining a sequence of operations, which lets you work cleanly with immutable data without storing a lot of intermediate values.</blockquote><blockquote>For example: you manipulate a sequential data structure declaratively by chaining filter, map and reduce calls to produce a new one.</blockquote><p>The whole point here is to reduce the amount of verbose code we would normally write to process things like lists into a few lines.</p><p><strong>filter</strong>: select the elements you want<br><strong>map</strong>: transform the selected elements<br><strong>reduce</strong>: combine the results (you can also use <strong>fold </strong>here)</p><p>This approach has the advantage of make code shorter and much easier to read. You can usually figure out what is happening at a glance. The downside is that not everything can be modeled this way and it can be super hard to figure out how to create a proper sequence to accomplish your goals. It takes time and a lot of practice to get this one right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*iIF1KDWq7VbVZk6SzcnIOQ.jpeg" /><figcaption>Sample code</figcaption></figure><p>As you can see, we easily filter for anything greater than 7, times it by 2 and sum it all up. All in a single line.</p><p>This pattern relies on declarative data manipulation, which is higher level than an iterative approach and sometimes higher level than a recursive one. It’s a lot like writing a SQL statement to search a relational database versus iterating over lines in a flat file with the same data.</p><h3>Function Builder</h3><p>This is a Creational Pattern, which should sound familiar to you if you’ve experience with OOP patterns.</p><blockquote>The point is to create a function that creates functions dynamically.</blockquote><p>Based on the input, you have a higher-order function that will return a custom function to suit your needs. This is great for modeling patterns.</p><p>It is also used for when you have static data that you need to use as the basis for some action. For example: calculating percentages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQ9Olx9aOhiOcn1O584iWQ.jpeg" /><figcaption>Calculating Percents</figcaption></figure><p>Pretty cool right? There are lot more cool things you can do with this pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngDcMCeKh2-op8u6_Tjczw.jpeg" /><figcaption>Function Transformation</figcaption></figure><p>You can use this pattern to transform one function into another. An example of this would be negation. If you have a function that returns true for one thing, you can easily create a function that returns the negated version of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r5McI4XecaYOvtdaiezU8w.jpeg" /><figcaption>Function Chaining</figcaption></figure><p>Another cool thing you can do is chain functions. You can take a list of functions and combine them together to create an even larger function. This is similar to the Decorator Pattern, where multiple decorators, each of which does one part of some task, are chained together.</p><p>You’ll see these a lot in web application. These chains allow your application to do anything that needs to be done before handling a request(i.e. decryption, decompressing the request, checking authentication credentials, logging to a request log, etc).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6SLG1lsF2xsW3ulYUjmIzw.jpeg" /><figcaption>Partially Applied Functions</figcaption></figure><p>Lastly, this technique is very useful when creating partially applied functions. If you’ve read my earlier articles, you would know that a partially applied function is one where only a subset of the arguments for an input function have been applied. The resulting function has fewer arguments than the original and keeps track of the arguments already passed in when it was created.</p><p>Lots to digest. There are still more patterns to go over. But this article is already really long. So, I’ll finish the rest next time.</p><p>There’s more to all of this. You can use these patterns with some OOP patterns. You just have to make some modifications first. I will do an article on these changes next. Like with anything in coding, the best way to let this stuff sink in is to use them. And we will. I’m almost done with these intro stuff, and I understand some of you who have read my first article have been a bit restless to get started on the project. I will do a tutorial for building a file management system really soon. It’s not going to be massive or super complicated. But it will display some of these patterns for you.</p><p>Before I get to the tutorial on the bidding system, I have to do a few more articles on concurrency, OOP patterns, Akka, Slick and Transaction models. I know. Lots of stuff. But, it will be worth it. So, hang in there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*r4MtzT00W6bLwQgUkkl-YQ.jpeg" /><figcaption>Don’t hate me.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9be81d843900" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional vs Object Oriented Programming]]></title>
            <link>https://medium.com/@kasa288/functional-vs-object-oriented-programming-10872e5ef439?source=rss-afac825c346b------2</link>
            <guid isPermaLink="false">https://medium.com/p/10872e5ef439</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Jaya]]></dc:creator>
            <pubDate>Sat, 20 May 2017 02:26:07 GMT</pubDate>
            <atom:updated>2017-05-26T00:12:32.551Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey guys, sorry for the delay between articles. I’m gonna talk about the difference between FP(Functional Programming) and OOP(Object Oriented Programming) in this article, and when it’s best to use each one.</p><p>Anything you can do with one style, you can do with the other, in most cases. But, one may be better than the other depending on the problem you are trying to solve. The styles do not restrict what kind of programs you write, but how you write them. That being said, no one style is always the best. It’s best to know both, so you can best tackle any given situation with ease. So, let’s get to it!</p><h4>Object Oriented Programming</h4><p>This is the most well known paradigm. As the name suggests, at the center of it all is an object. Objects contain both data and the functionality that operates on that data. The best was to describe this is to use the car analogy.</p><p><strong>Abstraction:<br></strong>You can’t build a car in one go. You have to split it up into smaller pieces. Not so small that it’s the smallest detail possible. But, not so large that it becomes too large to manage. Basically, you’re splitting up a complex object into smaller components.</p><p><strong>Encapsulation:<br></strong>Once you have broken the car down to it’s parts. You have to think about the characteristics of those parts. For example: the radius and width and the usage of a tire. In the same sense, you’re gonna build your car by putting all the pieces together: object composition. Encapsulation is basically the grouping of data and functionality to operate on that data. This makes your code more modular.</p><p><strong>Inheritance:<br></strong>There are many kinds of tires. Snow tires, Winter tires, Summer tires, etc. They all have similar characteristics, and certain differences. You wouldn’t want to write a separate class for each tire. This best thing to do is create a template which contains common features and then create special classes that contain specialized code. Basically, you’re special tires inherit common features from the parent: tire. This makes your code more reusable.</p><p><strong>Polymorphism:<br></strong>This is the last part. When you drive a car, you don’t need to know how everything works. You use use the gas pedal, steering wheel and gear shift to interact with the car. You have one or more interfaces for interacting with the overall program, and you have no idea of the inner workings of the code. This makes sure that no one other than you the creator can mess with your code.</p><h3>Functional Programming</h3><p>The key to Functional Programming is in the name: functions. FP is about immutability and composing functions rather than objects. Let’s go over the basic traits really fast:</p><p><strong>Functions are first class. </strong>They can be passed around, dynamically created, stored in data structures and treated like any other first-class object.</p><p><strong>Use pure functions. </strong>A pure function is a function with no side effects. By programming with pure functions, you will notice an <strong>increase in modularity </strong>which makes code easier to test, reuse, parallelize, generalize, and reason about.</p><p><strong>Functions can be composed. </strong>This is kinda like encapsulation in OOP. You can build larger functions by combining smaller functions together. Remember, functions are first-class.</p><p><strong>Expressions are preferred over statements</strong>. Expressions yield values. Statements do not and are there to help you control the flow of the program.</p><p><strong>Data is immutable</strong>. Instead of modifying a data structure, a new one is efficiently created.</p><p><strong>Data is transformed, not modified</strong>. Since data is immutable, it has to be transformed. So, when you pass a data structure to a function, a new one comes out and the one passed in is left unmodified.</p><p>The common thread here is that there are no side effects. But what does that mean? How can you write that has no side effects?</p><p>No side effects means that the code is stateless. There is no observable effect on the execution of the program other than to compute the result given its inputs. This is due to the idea of <strong>referential transparency</strong>. An expression is referentially transparent if for all programs, all occurrences of the expression in the program can be replaced by the result of evaluating the expression, without affecting the observable behavior of the program.</p><p>For example: 1 + 2 will always equal 3. In that sense, it is a pure function because the output never changes for the given inputs. So, anywhere you see 1 + 2, you can just replace it with 3 and see no adverse effects in the overall execution of the program.</p><p>Referential Transparency lets you take advantage of the substitution model. You can think of expressions like you would in algebra. You can solve a large equation by replacing variables with their values, and reduce it to its simplest form. You’re substituting equals for equals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*hGB0JX3JfFbftd3dI6x4CQ.jpeg" /></figure><p>As you can see on the right, x is referentially transparent. No matter how many times you call reverse or any other method on it, the output value is always the same. There are no side effects. As such, you can substitute x with it’s actual value and still get the same output. This is great when you are writing code that needs to run concurrently; you do not have to worry about any side effects leading to issues. Now let’s see some code with side effects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*Vj01hNrMQHRlnslHiwenZg.jpeg" /></figure><p>As you can see, the reverse function of StringBuilder is pure, but the append function is not. Each time you call append, the output value changes. This means it is not referentially transparent. In a concurrent program, this could be disastrous. Don’t worry though, any function with side effects can be split into a pure function at the core, and one or more functions with side effects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*m5oQJyQlotKFaj8YNAQ60w.jpeg" /></figure><p>Let’s go over the code in the above example. We created a function declareWinner which prints the Player with the highest score. Simple right? Now what if we wanted to find the Player with the highest score in a List or other data structure? What if we wanted to reuse portions of the code? Can’t exactly do that with the first definition of declareWinner.</p><p>But, if we split up the function into a pure function and one with a side effect. We can do exactly that. As you can see, we can go through a list of players and find the player with the highest score very easily. It also made our code more modular and lets us compose functions.</p><h3>Imperative Programming</h3><p>This is simply about programming with statements that modify the program state. We’ve been doing this so far with OOP and FP. By extension, you can mix principals of FP and OOP as needed. They are not mutually exclusive. They’re just options for tackling certain problems in an optimal fashion.</p><p>For example: Java is a classic OOP language. But, as of Java 8, it has become more functional by supporting lambda functions. It’s not entirely functional, but it is getting there.</p><h3><strong>Use Cases</strong></h3><p>With FP, the thing to remember is that for a specific input, the output will always be the same, and the input is always immutable. There are no state changes. So, whenever you need to write thread safe code, go with FP.</p><p>With OOP, state changes are the norm. A specific input does not always lead to the same output. For example: think about a search engine. Google does not always return the same results for the same search key. This goes against FP principals. So, in this case, use OOP.</p><p>There are more situations where one may be better than the other. Memory usage tends to be higher in OOP because everything is an object. FP has to create a new copy of a immutable data structure every time you add a new element. Each one has it’s own drawbacks.</p><p>Hopefully, that was a pretty good description of the differences between the two. Sometime soon, I will do an entry on design patterns for FP. Obviously, they will be different from the ones from OOP. So, it is definitely important to know them. So, be on the lookout!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*-rb58XiDEoujyqbIC4M27A.gif" /><figcaption>How FP and OOP make me feel.</figcaption></figure><h3>Edit</h3><p>There are a few things I would like to point out:</p><p>Java is not entirely an OOP language. It has primitive and static members neither of which are objects. However, Scala is an entirely OOP language. Sure, you can write programs that are a mix of FP and OOP in Scala. But, in Scala, everything is an object, even functions.</p><p>So, why choose it over Java? Well, Scala supports all FP concepts, while Java only supports a few. This gives you access to a lot of powerful constructs like pattern matching, etc. You have access to any library that is available to Java. Lastly, it runs on the JVM. It may not run at the same speed as Java code, but you trade a few microseconds for a whole load of functionality.</p><p>In terms of <strong>use cases</strong>, let me expand on what I have already said.</p><p>If you have to build UI, obviously, you’re gonna go with OOP. Everything in this situation is an object.</p><p>If you have <strong>many different related data types</strong> that share functionality and plan to create more in the future, you will probably need to make use of <strong>inheritance</strong>. This will let you create modular and reusable code. Go with OOP.</p><p>If you only have a <strong>few data types</strong>, but many operations to perform on them, and are unlikely to add new types in the future, you do not need inheritance. Go with FP.</p><p>If a specific operation can be modeled like a math operation, go with FP. This may seem confusing, so I’ll expand. Say you want to write a program that adds things together. You could do this with OOP, but it is much easier to do this in FP. Instantiating an object takes time and space. Why bother with all that?</p><p>FP is generally great at modelling operations that seem to follow a mathematical pattern(ex: recursive methods). If you can model a program as a mathematical proof, go with FP. That’s honestly the best advice I can give you.</p><p>Neither of these paradigms are mutually exclusive. You can write better programs if you use a combination of the two. You just need to know when to use which one. So, go experiment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10872e5ef439" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Tutorial Part 4]]></title>
            <link>https://medium.com/@kasa288/scala-tutorial-part-4-baeb4b2425cd?source=rss-afac825c346b------2</link>
            <guid isPermaLink="false">https://medium.com/p/baeb4b2425cd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Jaya]]></dc:creator>
            <pubDate>Mon, 08 May 2017 02:24:54 GMT</pubDate>
            <atom:updated>2017-05-08T02:24:54.871Z</atom:updated>
            <content:encoded><![CDATA[<p>This is gonna be the last introductory piece. We’re just gonna go over a few more basic topics such as currying and then it’s onto the good stuff. This specific article is gonna cover function composition, and how you can create functions dynamically.</p><h3>Currying</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*jhcF7Aty7-eZrns_LnDWjw.jpeg" /></figure><p>Currying is when arguments are passed in separate argument lists instead of one long one. In other words, you are taking a function that <strong>takes <em>N</em> </strong>arguments and turning it into a <strong>chained series of <em>N</em> functions each taking <em>1</em> argument</strong>. You can call these functions without providing all the argument lists, and you get a function back. You simply put multiple argument lists after the name of the method.</p><h3>Partial Functions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*HLA4MbDIHeTlJaunOy-RYg.jpeg" /></figure><p>Remember, a function works for every argument of the defined type. For example:a function that takes an Int and returns a String will take any Int and returns a String. A <strong>Partial Function </strong>is only defined for certain values of the parameter type. So, in the above example, a partial function may not accept every argument. You’re only accepting a small subset of input parameters. You’re probably thinking, why bother with this topic? You’re just validating a parameter. Remember, this is about function composition.</p><p>Scala has a type called PartialFunction, which has a lot of cool built in methods to help you out. In the above example, we used pattern matching and function composition to create a function from multiple other functions. As you can see, you need to make sure you cover all your bases when composing functions. I did not define partial for all input values, so I got a MatchError, which would be terrible during runtime for a real application. By the way, you can check if a function is defined for a specific value using the isDefinedAt method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*LwasF2If8hcZlBttpow66g.jpeg" /></figure><p>One last thing, <strong>PartialFunction is a subtype of Function</strong>, which means it can be used in a lot of different places to write some really cool code. For example, you can pass it in a case statement where a Function is expected.</p><p>Don’t worry too much about what a case class is just yet, we will get to that in later articles. For now, just know that I used to quickly create a new type.</p><h3>Pass-By-Name</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*VyJPKHIGhtmuICr7C0hWlg.jpeg" /></figure><p>The normal way that arguments are evaluated is called pass-by-value.<br>For <strong>pass-by-value</strong>, complex expressions are evaluated first, then the value is passed into the function. With <strong>pass-by-name</strong>, the code for an expression is bundled up into something called a Thunk that can be executed later.<strong> </strong>The Thunk is executed every time the name is used inside of the method. Anything defined using the “=&gt;” syntax is a pass-by-name value. For example:if you pass a function as a parameter to another function, that parameter function is pass-by-name. But, it is not limited to functions alone. You can do this with values as well, just use the “=&gt;” syntax.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*mH8iwdGqTLhyXHg7-qE3hg.jpeg" /></figure><p>In the above example, there is no real difference in the way the two method are executed. However, you will see a change when you pass an argument with a side effect. For example: you pass a code block that prints something. Something changed! This time, when you passed-by-value, the code block was evaluated only once. This is because after it evaluated the block, it saved the value of x. However, when you passed-by-name, the code block was evaluated twice, one for each time x was accessed.</p><p>By the way, “=&gt;” is called a rocket. So, if anyone asks you what a rocket is in Scala, you will know.</p><h3>Putting it all together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*57abCZ_dxa800mJMcXl6Rw.jpeg" /></figure><p>In the above example, I combined currying and pass-by-name to create a custom while loop using recursion. On each iteration, the loop evaluates the Boolean value cond, and if it is true, it evaluates the Int body. If I used pass-by-value, I’d hit an infinite loop. But, with pass-by-name, I essentially created a custom while loop. Even though, I used this loop to sum up the values from 1 to 10, I can easily modify this to do anything else with Ints.</p><h3><strong>Few other things</strong></h3><h4>Unimplemented code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*wwfIGISIaAc6Kn1OYDKeXQ.jpeg" /></figure><p>In Java, if you have unimplemented code, you can return a null value or a 0. However, a method calling this current method won’t know that it is unimplemented, unless you throw some kind of checked exception. Scala lets you return ???, which is of the type Nothing. If you call such a method, a NotImplementedError is thrown at runtime. This feature makes it easier to search for unimplemented code and cannot be ignored when it is executed because it produces a runtime error.</p><p><strong>Parameters</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*fSC3IRHa1JDXpJmuGrtI3Q.jpeg" /></figure><p>If you have ever worked with Python, you know what a <strong>named parameter </strong>is. Scala lets you do this as well. This is used to improve readability, and let you pass parameters in a different order than is defined without raising any errors.</p><p>Also, you can set <strong>default parameter values</strong>, just like in Python. This lets you leave out certain parameters when calling a certain method. Keep in mind, you still have to include the “()” like you would with any other method call, or as you can see, you will get an error.</p><p>These features are really useful when you want to overload a method, but not write the tedious amount of code that you would with Java.</p><p>Well, that’s it for the basics. You can now go out and build some pretty cool things with Scala. Next time, I’m gonna go over the basics of Object-Oriented Programming, Functional Programming, and Software Development. I know Scala has a lot of FP characteristics, but do not be fooled. Scala is just a better, but marginally slower Java. Keep a look out, things are getting interesting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*UzGr_h9pACsRCuNT9vCdgg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baeb4b2425cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Tutorial Part 3]]></title>
            <link>https://medium.com/@kasa288/scala-tutorial-part-3-9213bb5d5a89?source=rss-afac825c346b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9213bb5d5a89</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Jaya]]></dc:creator>
            <pubDate>Fri, 05 May 2017 23:30:56 GMT</pubDate>
            <atom:updated>2017-05-05T23:30:56.319Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m gonna cover some more List and Array methods this time, Options, and little bit of IO. If you haven’t already, take a look at <a href="https://medium.com/@kasa288/scala-tutorial-part-1-416d7eb4998f">part 1</a> and <a href="https://medium.com/@kasa288/scala-tutorial-part-2-ced4e6e214d5">part 2</a>. They are really short reads and have tons of examples on how to do everything. If you have any doubts or comments or corrections, feel free to let me know. Let’s get started!</p><h3>Get or Remove Elements</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*_4D7p4H4Q4-wfkv3aC0zJg.jpeg" /></figure><p>For the rest of this tutorial, much of the code will work with <strong>val nums</strong> which is an Array and <strong>val words </strong>which is a List.</p><p><strong>drop(n: Int) </strong>removes the first n elements and returns a new Collection. Key word: Collection. That means it is not limited to Arrays as shown in the figure.</p><p><strong>dropRight(n: Int) </strong>removes the last n elements and returns a new Collection.</p><p><strong>head</strong> gives you the first element and <strong>last </strong>gives you the last element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*8YwYPER-eaz55Q8hR0wtaA.jpeg" /></figure><p><strong>patch(from: Int, replacements: Seq[A], n: Int)</strong> produces a new collection by replacing <strong>n</strong> elements starting at the index given by <strong>from </strong>with values in <strong>replacements</strong>.</p><p><strong>slice(from: Int, until: Int) </strong>returns a new Collection with elements from <strong>from</strong> to <strong>until</strong>, with until being <strong>exclusive</strong>.</p><p><strong>splitAt(index: Int)</strong> produces a tuple after splitting the original collection at the given index.</p><p><strong>take(n: Int) </strong>and <strong>takeRight(n: Int)</strong> give you the first n elements and the last n elements, respectively.</p><h3>Set Manipulation Methods</h3><p>The following methods will look familiar if you have ever taken a discrete math class. It’s all set theory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*1TAQcsjOIGQnHcUqWI7HOw.jpeg" /></figure><p><strong>distinct</strong> produces a collection of all unique elements in a given collection.</p><p><strong>intersect(that: Seq[A]) </strong>produces a new collection that returns the intersection of the current collection and that.</p><p><strong>union(that: Seq[A]) </strong>produces a new collection that is the union of the current collection and that.</p><p><strong>diff(that: Seq[A]) </strong>produces a new collection that is the difference between the current collection and that.</p><h3>Utility Methods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*2SNCX9wFoZoDBFKUkfiNhw.jpeg" /></figure><p><strong>max, min, product</strong> and <strong>sum</strong> are self-explanatory, right?</p><p><strong>zip(that:Seq[B])</strong> produces a new collection of tuples containing elements from the current collection and that. The resulting collection is no longer than the smaller of the two input collections.</p><p><strong>zipWithIndex </strong>produces a collection of tuples by zipping the elements in current collection with their respective indices.</p><p><strong>tail</strong> returns a collection of all elements after the first element.</p><p><strong>mkString</strong> converts a collection into a String.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*inyF85fgNHRddDozTqQ0ng.jpeg" /></figure><p>Both Arrays and Lists can work with patterns. So, you can do some cool things like in the figure above. This is actually a really common practice in Scala, so you’re going to want to get used to working with this kind of code. At the bottom of the image, you will see some interesting things. You can convert a List to an Array and back. It is very easy, so you can make methods that take only Lists, word with Arrays and vice versa very easily.</p><h3><strong>Functional Methods</strong></h3><p>The following methods should be familiar to anyone who has worked with functional methods before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*xL3O82fX26ONkWZ9bRQP2A.jpeg" /></figure><p><strong>foreach(A =&gt; Unit) </strong>produces a Unit (void in Java) and performs the given lambda expression on each element. This means that if your lambda expression returns anything, it is ignored.</p><p><strong>map(A =&gt; B)</strong> produces a new collection by applying a lambda expression to each element.</p><p><strong>filter(A =&gt; Boolean)</strong> produces a new collection by filtering out elements in the current collection by applying a lambda expression to each element.</p><p><strong>split(delimiter: String)</strong> should look familiar to anyone who has worked with the method in Java. It splits a String based on the delimiter.</p><p>Obviously, you can mix and match these methods as much as you want. There is no restriction there. Just remember to save the outputs to intermediate values if you have really long combinations of these methods. This will improve readability.</p><h4>Predicates</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*8RIWN2Iuw8RzuakzMq9C4A.jpeg" /></figure><p><strong>count(p: A =&gt; Boolean)</strong> returns the number of elements that satisfy the predicate.</p><p><strong>dropWhile(p: A =&gt; Boolean) </strong>produces a new collection where all members <strong>at the front </strong>the satisfy the predicate have been removed.</p><p><strong>exists(p: A =&gt; Boolean) </strong>returns where or not there is an element in the sequence that satisfies the predicate.</p><p><strong>filterNot(p: A =&gt; Boolean) </strong>does the opposite of filter. It creates a new collection with the elements that do not satisfy the predicate.</p><p><strong>find(p: A =&gt; Boolean) </strong>returns an Option[A] with the first value that<br>satisfied the predicate.</p><p><strong>forall(p: A =&gt; Boolean) </strong>tells you if the predicate is true for all values in the sequence.</p><p><strong>indexWhere(p: A =&gt; Boolean) </strong>returns the index of the first element that<br>satisfies the predicate.</p><p><strong>lastIndexWhere(p: A =&gt; Boolean) </strong>returns the index of the last element<br>that satisfies the predicate.</p><p><strong>partition(p: A =&gt; Boolean) </strong>produces a tuple with two elements: a sequence of the elements that satisfy the predicate and a sequence of those that do not.</p><p><strong>prefixLength(p: A =&gt; Boolean)</strong> returns the number of elements at the beginning of the sequence that satisfy the predicate.</p><p><strong>takeWhile(p: A =&gt; Boolean) </strong>produces a new sequence with the elements<br>from the beginning of this collection that satisfy the predicate.</p><h4>Folds</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*Tkgxci2hOPI8xQbxw_5rfw.jpeg" /></figure><p><strong>foldLeft(z: B)(op: (B, A) B) </strong>is a curried method that produces an element<br>of type B. B is the type of the first argument to the function, the first argument to the operation, and the output of the operation. It works by going from left to right through the collection, and for each element it passes the accumulated value and the next collection element into the op function. The result is used as the accumulated value for the next call. z is the first value for the accumulator, and the last one is the result of the function.</p><p><strong>reduceLeft(op: (A, A) A) </strong>is a more restricted version of foldLeft. There is no initial accumulator, as the first call to op is passed the first and second elements. The output of that is then passed in with the third element and so on. The value after the last element is the result of the reduce.</p><p><strong>scanLeft(z: B)(op: (B, A) B) </strong>is like foldLeft, but it returns a sequence with all the intermediate results, not just the last one.</p><h4>A Few Others</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*EfF4EdhI-6LFlMn9pEra3Q.jpeg" /></figure><p><strong>flatMap(f: A =&gt; Seq[B])</strong>is like the map function, but is useful<br>when the function produces sequences and you do not want embedded Lists or Arrays (ex: List[List[B]]). It flattens the result to give you just a basic sequence.</p><p><strong>maxBy(f: A =&gt; B) </strong>returns the maximum element based on comparison of the B values produced by passing the elements of this collection into f.</p><p><strong>minBy(f: A =&gt; B) </strong>returns the minimum element based on comparison of<br>the B values produced by passing the elements of this collection into f.</p><p><strong>sortBy(f: A =&gt; B) </strong>produces a new collection with the elements sorted based<br>on the B values produces be passing the elements of this collection to f.</p><p><strong>sortWith(lt: (A, A) =&gt; Boolean) </strong>produces a new collection with the elements sorted based on the comparison function that is passed in.</p><p>Make sure you pay attention to the way capital letters differ from lower case letters in the above methods.</p><h3><strong>Option Type</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*38WcWvlMdpIuAHx_TEHcuA.jpeg" /></figure><p>Options are a great option when you want to avoid passing back null values. You’ll recognize this if you have ever worked with <strong>Optional </strong>in Java. There are two types: <strong>Some </strong>and <strong>None. Some </strong>holds a single value. <strong>None </strong>represents the absence of a value. By returning an Option or Optional, the goal is to avoid a NullPointerException. These objects are great when you use it in combination with <strong>match</strong> (Pattern Matching). You could get the value in a <strong>Some </strong>by using the <strong>get()</strong> method, but you will get an exception if you call this method on <strong>None</strong>. There is a way to get around this: use <strong>getOrElse(alternative: B)</strong>.</p><h3>Finally, Some IO</h3><p>Let’s read something from a file. We are gonna use <strong>scala.io.Source</strong> which we will instantiate with the <strong>fromFile()</strong> methods. A Source is actually an <strong>Iterator[Char]</strong>. You’re probably going to want to read one line after another, instead of one character at a time. We can do this by calling <strong>getLines() </strong>which returns an <strong>Iterator[String]</strong>.</p><p>Unlike a List or Array, once you use an Iterator, it’s contents are consumed, which means you <strong>can only use an Iterator once</strong>. This is like Streams in Java, and it is a very efficient way of going through files because it frees up memory once you’re done reading through the file. Iterator also has <strong>hasNext()</strong> and <strong>next()</strong>, which tell you if there are any elements, and gives you the element, respectively. You can iterate through an Iterator using higher order functions or a while loop. <strong>hasNext() and next() </strong>will come in handy if you do use a while loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*yNASIpAg-xv5v7-tiq_BJQ.jpeg" /></figure><p>The above code reads a text file contains numbers separated by commas. It reads each line, splits it up by the comma and maps the toDouble function to each value. Lastly, it converts the whole thing to an Array. Simple and elegant.</p><p>This method is great when out file contains values of a single type. But, if each line consists of a mix of String, Int and Double, it would be a better option to use a while loop and read value at a time and map it properly. Feel free to play around and see what you can do. Best way to learn anything.</p><p>That’s it for this time. Next time, I’m gonna go over currying and a few more basics. But, as of now, you know enough to get started and write rudimentary applications. Go out an explore!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*VPB1KcWRh-sRqVCOXwri9A.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9213bb5d5a89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Tutorial Part 2]]></title>
            <link>https://medium.com/@kasa288/scala-tutorial-part-2-ced4e6e214d5?source=rss-afac825c346b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ced4e6e214d5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Jaya]]></dc:creator>
            <pubDate>Fri, 05 May 2017 18:45:55 GMT</pubDate>
            <atom:updated>2017-05-05T18:45:55.021Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second part of my tutorial series for Scala. If you haven’t already, be sure to check out the <a href="https://medium.com/@kasa288/scala-tutorial-part-1-416d7eb4998f">first part</a>. We’re gonna cover declarations, scopes, basic libraries, and a few collections. So, I have you’re ready to get started. Keep in mind, I make the assumption you have a background in coding already, have all the necessary tools already installed and have an idea of what a functional language is. Without further delay, lets get to it!</p><h3>Object Declarations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*tWPMR1wM4hBOJVX8537QAw.jpeg" /><figcaption>Object Declaration</figcaption></figure><p>Lets start with the <strong>object </strong>keyword. We can use this to create a singleton.As you can see on the left, you cannot instantiate an <strong>object</strong>. The syntax is as follows:<br><strong>object </strong><em>ObjectName{<br> methods<br>}</em></p><p>This creates an anonymous class, and creates a single instance of it called Square.</p><p>Methods are defined using the following syntax:<br><strong>def </strong><em>methodName(argList):OutputType </em>=<em> expression</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*aE7B8H9aH4z2heLvZ61YsA.jpeg" /><figcaption>Inferred Return Types</figcaption></figure><p>You don’t have to specify the OutputType for non-recursive methods, but you should include them anyways, especially for methods where it is not clear what the return type may be. In the example to the left, you have two versions of the same method. They differ in return type only. The <strong>first version</strong> could infer that the return type is <strong>Double</strong>. The <strong>second version </strong>is returning <strong>Unit</strong>, but if we want Double, this would be a problem. So, be on the safe side: just specify your return type.</p><p>In the examples above, we returned values without having to use a <strong>return</strong> keyword. In Scala, you can still use <strong>return</strong>, but you do not need to. Methods in<br>Scala are considered expressions, who’s result is whatever is produced by their last statement. You don’t need to use it even if you’re returning something mid method. Cool right?</p><p>Classes and Traits are declared using the following syntax:<br><strong>(class </strong>or<strong> trait) </strong><em>ClassName(argumentlist){<br> method declarations and variables<br>}</em></p><p>Obviously, the <em>argumentlist </em>and the <em>brackets </em>around them are optional. I will get into more detail about these in later articles.</p><p>Keep in mind, <strong>object, class and trait</strong> can be declared at the top level in Scala applications. They <strong>do not have to</strong> be inside something else. Does not mean they can’t be. Basically, still the same rules as Java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*foMCwdhAfKEhC82Uqp2giw.jpeg" /><figcaption>Types in Scala</figcaption></figure><p>Now, I want to go over in this section is <strong>type</strong> declaration. They let you combine multiple types to create a custom alias. They are really useful for shortening code and saving time. Can you imagine typing <em>(Double, Double, Double)</em> a thousand times? Yikes.</p><p>Let’s go over scope. Scope in Scala follows the same rules as Java. Scope is limited to the curly braces that surround them, or the block they are defined in. So, nothing new there, assuming you have experience with Java.</p><h3>Libraries</h3><p>You have access to all the libraries available to Java, <strong>and </strong>Scala. This is because Scala code compiles and runs on the JVM. Let’s go over a few.</p><p>Quick Note: imports follow similar rules to Java. Instead of a <strong>*</strong> for importing everything, you use a <strong>_</strong>.</p><p>By default, Scala imports the following libraries for you:<br>1. import java.lang._ which is imported by default in Java.<br>2. import scala._ imports everything in scala package, so you do not need to specify the scala prefix later on.<br>3. import Predef._ which is short for scala.Predef._ and shows that imports are additive.</p><p>Because of import <strong>2</strong>, we can shorten imports like <strong>import scala.io.StdIn._</strong> to <strong>import io.StdIn._</strong>. Say for instance, you want to import only a few of the features of a package. Using <strong>_ </strong>would be inefficient. Scala lets you do the following: <strong>import io.StdIn.{readInt, readLine} </strong>which imports only the methods specified inside the braces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*BJajF069rTlY5dVUHJeAHA.jpeg" /><figcaption>Selective imports</figcaption></figure><p>Say you have two packages with objects that have the same name. Scala has a very simple solution for this: rename or hide certain names. For example: the java.util package contains List, Map, and Set. You can find items with the same names in Scala Collections. Sp, using <strong>import java.util._</strong> would be <strong>inefficient</strong>. So, you could do something like in the image above. We <strong>import Java List and rename it as JavaList</strong>. Also, we make sure that Map and Set are not imported by setting them to <strong>_</strong>. The <strong>underscore at the end</strong> brings all other items from the java.util package <strong>without modification</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*yZ8IEkpplcLFu0OmDYCJTw.jpeg" /><figcaption>A Sample Class that gets input</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*i2cLo5SqJ60dfRbKCzzqew.jpeg" /><figcaption>SampleInput usage</figcaption></figure><p>Keep in mind, that the () after readLine and readInt are not necessary. But, you should include it because you do not want unexpected side effects.</p><h3>Basic Collections</h3><p>In Scala, all collections are part of the standard library. In Java, arrays are post-fixed with <strong>[]</strong>, because they are language-level constructs and not part of the collections library. Let’s start by going over Array, List, and Range. These are ordered sequences of a specific type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*emUSzncT5GaDZz-LPhCMcw.jpeg" /><figcaption>Array and List usage example</figcaption></figure><p><strong>Array </strong>is a fixed-length, mutable sequence. You can specify type as follows: Array[<em>Type</em>]. <strong>List </strong>is a immutable sequence. The above code <strong>treats List and Array objects as functions</strong>, and passes them arguments that are supposed to go into a new collection of that that. The type of the content is easily inferred by Scala. You can easily access elements by their index in both collections. Lastly, remember that Array is mutable and List is immutable. So, <strong>you can reassign values in an Array, but if you try the same in a List, you will get an error</strong>. I know, its weird that you cannot modify a List like in Java. But, you’ll see the benefits of it later on.</p><p>You can create customs using helper methods. I will go over a few of the common ones.<strong> Remember, you can use these methods with List and Array</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*_61v0pO51bHyBa6Xm76I2w.jpeg" /><figcaption>Array.fill example</figcaption></figure><p>As you can see in the above example, you can use the <strong>fill </strong>method to create Array objects. In the first example, we created an Array with ten 1’s. In the second one, we create an Array with 10 “a”’s. The last example creates an Array with 10 random values between 1 and 0. We use two cool features called <strong>currying </strong>and <strong>pass-by-name</strong> here; I will go over these in depth later. Trust me, they’re cool. For now, I will give a simple explanation. Currying is where arguments to a function are passed as separate argument lists instead of<br>a single, longer argument list. This lets you build partial functions and customize them as needed. Java and Scala are normally pass-by-value. Arguments are evaluated before the function or method is called, and the value it evaluates to is passed in. Using pass-by-name, the code itself is<br>passed in, and it is re-evaluated every time it is used. You can see this is the last example, which calls math.random as needed. This gives us 10 possibly distinct values instead of just one. Cool right? The only limitation is that the code used to initialize the values does not have any information about the index that the value is going into.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*hE6EWWMNxU2wLyMrZvO9iQ.jpeg" /><figcaption>simple tabulate examples</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*w7NlslPGFxbbx5zpIm0DMQ.jpeg" /><figcaption>tabulate with a large lambda</figcaption></figure><p>You can overcome this limitation with <strong>tabulate</strong>. This function is very similar to fill, it still curries two argument lists. The first argument is still the length of the collection. The second argument is a function that takes an Int and returns a value. The input value is the index that the function is making the value for. The function that is passed can be a simple lambda expression or a complex one. This method is great if you want the values in the collection to follow a specific pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*USdOvxQubwB7rxfpAiAGRQ.jpeg" /><figcaption>new operator in Scala</figcaption></figure><p>Let’s not forget about the <strong>new</strong> operator, you can use it to create an Array. It’s not common to use it in Scala, but you can if you want to. Scala developers tend to avoid using the new operator especially with Strings. Remember, the default value for Strings is null, just like in Java. You can’t instantiate a List the same way because List class is abstract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*xywo05mb4o9kw6ffruVu-A.jpeg" /><figcaption>cons operator example</figcaption></figure><p>To create a List, you can use the <strong>cons(::) </strong>operator. Lists are immutable, so you cannot modify the values or add more. However, it is efficient to make a new List by prepending an element with cons. <strong>Nil </strong>stands for an empty List; specifically, List[Nothing]. Remember operators are right associative. So, you can group elements together with parenthesis and use the dot operator. The cons operator is great when you want to efficiently build a collection, but don’t know how many elements it will have. If you ahead of time, just use an Array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*cWAIusz9RQWw4WjL4wusaw.jpeg" /><figcaption>example usage of cons</figcaption></figure><p>The above code gives you a quick example of how you can use the cons operator to get user input. Remember to use <strong>var</strong>; if you use val, you cannot modify the list reference. Using cons does not append to the original list, it creates a new one, and val will not allow you to change the reference. We used <strong>List[Int]()</strong> because if we used Nil, it would not compile. Lastly, we used <strong>reverse </strong>because cons does a prepend, and list comes out in reverse order. You could just append it, but it’s not efficient. This is not the most efficient solution, obviously. It would be better to just to this whole thing recursively, like in the next figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*xBvZ4Xca-e0Mun-fw8LBsQ.jpeg" /><figcaption>readList with recursion</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*KCdNkkxsnnq-JkQLcfF0lA.jpeg" /><figcaption>Range example</figcaption></figure><p><strong>Range</strong> represents a fixed set of elements. You use these when you use for loops in Scala. The line <strong>1 to 10</strong>, is calling the to method of Int on 1 and passing 10 as a parameter. The to method is inclusive, there is an exclusive version called <strong>until</strong>.</p><p>Feel free to play around. Try creating a list of Fibonacci numbers or something. Sky’s the limit. I’ll try to do another entry soon and go over some more useful List and Array methods. So, be on the lookout!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ced4e6e214d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Tutorial Part 1]]></title>
            <link>https://medium.com/@kasa288/scala-tutorial-part-1-416d7eb4998f?source=rss-afac825c346b------2</link>
            <guid isPermaLink="false">https://medium.com/p/416d7eb4998f</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Jaya]]></dc:creator>
            <pubDate>Thu, 04 May 2017 05:49:41 GMT</pubDate>
            <atom:updated>2017-05-04T14:46:57.430Z</atom:updated>
            <content:encoded><![CDATA[<p>Since the project we are doing with Play is going to be done mostly in Scala, it is important that we have the basics down before we proceed. I’m gonna make a few assumptions before we start. I’m going to assume that you already have Scala installed and know how to use Scala REPL. I’m assuming that you are experienced with Java because there are a decent amount of similarities between the two languages. Lastly, I assume you know what a functional language is and how it differs from an imperative language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*dFgedTAQBcrE_cfVQgvY-g.jpeg" /><figcaption>Type Inference</figcaption></figure><p>Let us start with variable declaration. If you have experience with Java, you know that the reference to each variable specifies the type. In Scala, that is optional. Scala does local type inference based on the information on the current line. However, you can specify the type if you want to.</p><p>The next step is understanding the difference between <strong>val</strong>, <strong>var</strong> and <strong>def</strong>. “<strong>val</strong>” is similar to a variable marked <strong>final</strong> in Java. You CANNOT modify the value of a variable marked <strong>val</strong>. “<strong>var</strong>” is a non-final, modifiable variable. In other words, you can change the value of a <strong>var</strong>. Last is <strong>def</strong>, which is used to define methods. Scala follows the same rules as Java for naming variables and methods, so there is nothing new to learn in that sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*-tpAHB5-0S32sNpj5uMPmg.jpeg" /><figcaption>Primitives in Scala</figcaption></figure><p>Let’s go over the primitives in Scala. You have all the same primitives as Java, and a few new ones. The only difference is that the first letter of each primitive is capitalized.</p><p>The two new types in Scala are <strong>tuples</strong> and <strong>Unit</strong>. Unit is equivalent to void in Java (i.e. nothing is returned). <strong>Tuples</strong> are pairs of values. As you can see in the image to the left, (1, 0) represents a <strong>tuple</strong> of <strong>Int</strong>s. Remember, every value in Scala is an object, so you can call methods on all values regardless of their type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*EIBHkjSUfvcSCFby-CR5vA.jpeg" /><figcaption>Strings in Scala</figcaption></figure><p>Strings work much the same way they do in Java. You can concatenate with the <strong>+</strong> operator or you can use the <strong>$ </strong>to interpolate strings. You just have to remember to put the <strong>s </strong>in front of the double quotes. As you can see from the last line in the image, there are plenty of ways you can play around with Strings.</p><h3>Expressions vs Statements</h3><p>An expression is a piece of code that has a value, a type and evaluates to something. This is different from a statement, which just does something.<br>Variable declarations are statements that associate a name with something, but they do not provide any value as a result.</p><p>In Scala, most things that are not declarations are expressions. Things that look like operations are actually methods. When you type <strong>4+5</strong>, Scala sees <strong>4.+(5)</strong>. It is not converting the 4 into a float, it is calling the <strong>+ method</strong> of the <strong>Int </strong>object. The cool thing here is that you can use methods that have alphabethic names like you would with operations. You can use <strong>4.min(5)</strong> or <strong>4 min 5</strong>. How cool is that?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*1lvD1pnz23I_Q2WFsOXudg.jpeg" /><figcaption>eq in Scala</figcaption></figure><h3><strong>== is Scala</strong></h3><p>In Java,<strong> ==</strong> is used to compare references and <strong>equals()</strong> is used to compare the actual values for equality. In Scala,<strong> ==</strong> is calls <strong>equals() </strong>for everything built into the standard library. If you need to check for reference equality, use the <strong>eq </strong>method.</p><p>There are a lot of cool things you can do in Scala like “hi” * 5, which prints “hihihihihi”.</p><h3>Lamba Expressions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*MhV5kVqZ7IhN_41DCrv15w.jpeg" /></figure><p>A lambda expression is a functional programming construct that allows you to write a function as an <strong>expression</strong>. As you can see, you do not need to specify the parameter types; Scala can figure that out really easily. But, it won’t hurt you to do so. You do not have to use the brackets when specifying the input parameters. In the example above, we created a function square, which takes a double, and returns a double. This is specified in the 2nd version as <strong>(Double) =&gt; Double</strong>. It could also be written as <strong>Double =&gt; Double</strong>. You can create lambda functions with a variable number of parameters as well.</p><p>Also, if your lambda has only one parameter, and you already specified the type, you can use the <strong>_ </strong>notation, which maps the input parameter directly to the function. This is just a useful way of shortening the code. The rules for using the <strong>_ </strong>syntax are complex, so if you run into any weird errors, just switch back to the normal notation. It is the simplest solution, and will make your life a lot easier that finding the source of the bug. But, if you really want, you can always debug the problem so you can use that specific notation.</p><p>The last thing to remember about lambdas is that they are meant to be short and simple, not multi line expressions. If it is more than a few lines long, just make it a function by changing the <strong>val</strong> to <strong>def</strong>. They will both work the same when passed to a function that expects a lambda, but this is just a best practice thing.</p><h3>Conditionals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*QQWKlfEx1l3yI372DjFXGg.jpeg" /></figure><p>Your classic <strong>if</strong> statements are the same as in Java. So, there is nothing new to learn there. Your <strong>if</strong> statement will take a boolean expression and if it evaluates to true, it will run the block that follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*3wJjmkAbx6punPzs4biknw.jpeg" /></figure><p>One of the coolest features in Scala, is <strong>pattern matching</strong>. This is similar to a Java <strong>switch </strong>statement, but on steroids.</p><p>Each case has a <strong>pattern</strong> and an <strong>optional if</strong> statement that you can use to filter the results further. Each case is checked for a match sequentially, until a match is found. When you create a match statement, make sure you have a case statements that match every possible outcome. In later tutorials, I will show you the real power of this feature. It will blow your mind.</p><h3>Loops</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*IqsjZDT3r419vpwCn2RhTw.jpeg" /><figcaption>Loop examples</figcaption></figure><p>While and Do while statements are the same as in Java. For loops work the same, the syntax is just a little different.</p><p>There are two options for the syntax for a <strong>for</strong> loop. This first is <strong>for<em>(pattern &lt;- collection) body</em></strong>. The <strong><em>pattern &lt;- collection </em></strong>part is called a generator. The for loop can have multiple generators separated by semicolons. The pattern can be something really simple (like in the example) or something complex. If an element does not match the pattern, it is simply skipped over.</p><p>The second is <strong>for<em>(pattern &lt;- collection) </em>yield<em> body</em></strong>. By adding yield, you are turning the for loop into an <strong>expression </strong>which <strong>produces a new collection</strong> with the values that the body evaluates to on each iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*ntHAfHGkLxRQBmwBcq4gpg.jpeg" /><figcaption>Example of a Complex For Expression</figcaption></figure><p>The last thing to remember is that you can specify if statements and variable declarations to further filter out the values in the generator. These are also separated by semicolons. You can also use braces and multiple lines to improve readablitity.</p><p><strong>Error Handling</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*Z9l4SXdK8z-dGe614xNqvg.jpeg" /><figcaption>Example of Exception Handling</figcaption></figure><p>The last thing I’m gonna go over is exception handling in Scala. Again, there is not much of a difference from Java. You still have a <strong>try</strong>, <strong>catch</strong> and <strong>finally</strong> block. The <strong>catch</strong> or <strong>finally</strong> block can be left out. However, in Scala, the <strong>try/catch</strong> is an <strong>expression</strong>. Therefore, you will want the <strong>return type</strong> of the <strong>expression</strong> in the <strong>try block</strong> to match the <strong>return type</strong> of the <strong>case statements</strong> in the <strong>catch block</strong>.</p><p>The general syntax for these blocks is as follows:</p><p><strong>try</strong><em><br> expression<br></em><strong>catch </strong><em>{<br> </em><strong>case </strong><em>pattern =&gt; expression<br> …<br>}<br></em><strong>finally </strong><em>expression</em></p><p>As in Java, the <strong>finally block will always run</strong>, whether an exception is thrown or not.</p><p>That’s it for now. Next time, I will go over method and object declarations, scope, collections, various built-in methods and a little IO. This stuff will be the bread and butter of much of your work in Scala. I’m also gonna start doing articles on the basics of designing an auction system. I won’t get into the code right away, but I will give a decent outline of the design and best practices. So, be on the lookout for the next article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*BNlL9zfDguUmmv0oTgoWpg.gif" /><figcaption>My average reader after this article</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=416d7eb4998f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Play Framework with Scala]]></title>
            <link>https://medium.com/@kasa288/intro-to-play-framework-with-scala-f227806e7049?source=rss-afac825c346b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f227806e7049</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[play-framework]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Jaya]]></dc:creator>
            <pubDate>Wed, 26 Apr 2017 22:57:14 GMT</pubDate>
            <atom:updated>2017-04-26T22:58:36.692Z</atom:updated>
            <content:encoded><![CDATA[<p>Before we get started, I’m going to go over the basics. To work with Play, you will need the following:</p><ol><li><a href="https://www.scala-lang.org/download/">Scala</a></li><li><a href="http://www.scala-sbt.org/download.html">SBT</a></li><li><a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html">Java SDK</a></li><li><a href="https://www.jetbrains.com/idea/download/#section=windows">IntelliJ IDEA</a></li></ol><p>If you can, get your hands on IntelliJ IDEA Ultimate. But, you should be good to go if you use Community. If you have issues with IntelliJ Community Version or want to use Eclipse, that&#39;s not a problem. You can always use <a href="https://www.lightbend.com/activator/download">Lightbend Activator</a>. Be sure to follow the directions provided by their respective sites when setting up the above requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*ESsCaMD_iat_OrXAEHTUBQ.jpeg" /></figure><p>To the right, you will see the basic directory setup. All your code, Java or Scala, will go in the “<em>app</em>” folder. Note: if you do not see the model folder, DO NOT FREAK OUT. I added that folder manually.</p><p>The “<em>conf</em>” folder contains your configuration files and routes file. The “<em>public</em>” folder contains all your resources. Lastly, the “test” folder is obvious. For more info on the file structure, check out this <a href="https://www.playframework.com/documentation/2.5.x/Anatomy">link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*23G1C4STVCAYEeVxf_lKog.png" /><figcaption>Framework Architecture provided by Play website</figcaption></figure><p>The image to the right is this <a href="https://www.playframework.com/documentation/1.2.2/images/diagrams_path">link</a>. It outlines how a REST service works in Play. The <strong><em>Router </em></strong>is provided to you by Play. It maps incoming requests to their corresponding actions within <strong><em>Controllers</em></strong>. Anyone who has worked with <strong>Spring </strong>should be familiar with what Controllers are. Controllers abstract away how HTTP requests and responses are handled from your application code. They act as your endpoints for a given set of actions. You’ll get a better idea of this once we start coding.</p><p>Your <strong><em>Model </em></strong>is part of your Business Layer, or your back-end. It handles all communications with your persistence solution. Last, is the <strong><em>Views</em></strong>, which handles how you present information to the end-user.</p><p>I’d love to into more detail about the basics of the Play Framework, but you can find all of that <a href="https://www.playframework.com/documentation/2.5.x/Philosophy">here</a>. Feel free to check out that link to learn more about what the framework is, and why you should use it.</p><p>My next article will be a quick intro into Scala and how to get a really basic application up and going. Don’t worry, there will be some coding, next time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*MvRL6vjUNx53HdJQYS_fAw.gif" /><figcaption>Fans will get it</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f227806e7049" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I’m going to start doing an development series starting tomorrow.]]></title>
            <link>https://medium.com/@kasa288/im-going-to-start-doing-an-development-series-starting-tomorrow-f2aa604a43a5?source=rss-afac825c346b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2aa604a43a5</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[play-framework]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Jaya]]></dc:creator>
            <pubDate>Mon, 24 Apr 2017 04:39:14 GMT</pubDate>
            <atom:updated>2017-04-25T22:19:29.508Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A Hello</blockquote><p>I’m going to start doing an development series starting tomorrow. I’m trying to get better with functional programming, asynchronous processing and deep learning. I know it’s a lot of different topics, but I feel that they all go hand in hand in today’s environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N0AUKlttflxzr8Ij-DfC7Q.png" /></figure><p>My first few posts will be on The Play Framework with Scala and Java. The tutorials I’ve seen so far are not very good at breaking things down, and just expect you to know certain things ahead of time. My posts will try to bridge the gap for new and seasoned learners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*1dCbi64_a9si5kN6RUe3NQ.jpeg" /></figure><p>By the end of the series, I’m going to show you how to design a simple auction system that processes real-time data.</p><blockquote>Keep in mind, I’m not perfect.</blockquote><p>I try to go by best-practices as much as I can. Also, Play doesn’t have detailed tutorials like Spring. So, much of what I do will be based on my own experience. That being said, I encourage everyone to comment and let me know if there’s a better way. Just remember to be respectful and cite sources if you can.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0XmZWVOGDoLWip38UpXWWg.jpeg" /></figure><blockquote>Into the wild green yonder!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2aa604a43a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>