fabiochiu/medium-articles huggingface dataset:
What happens when you slice the pie up
By: Carlos Henry
Tags: Self Improvement, Wealth, Relationships, Motivation, Copywriting

Stop looking at the whole pie.

I mean for you to not worry about everything that you need to do all at once.

My goal was to read one book per week.

This is what I saw successful entrepreneurs were doing, so I decided that I would follow in line.

I wanted to be just like them.

But unfortunately, there wasn’t enough strength in me to immediately jump to reading one book a week.

However I craved this lifestyle.

They were riding in yachts and travelling the world and I knew that I wanted this part, so I had to endure the reading as well.

So I tried reading so hard.

I couldn’t read a whole book but I could read a bunch of small social media posts and end up there for hours.

Then it hit me.

Why try to read the book as a whole instead of reading little by little?

I thought successful entrepreneurs just started putting in crazy amounts of work without really seeing what was happening behind the scenes.

One must become a student.

I watched countless videos and listened to hundreds of podcasts, but I was missing the reading portion.

First I started with a daily chapter.

Reading wasn’t my favorite hobby, but after following this model I began to fall in love with it to the point where I read one book five times before going on to the next.

I wanted to absorb everything.

My brother hated reading more than me and he started with reading a single page per day.

There’s no excuse why you can’t do that.

It only takes about 1–2 minutes to read a page, maybe even shorter than that depending on your reading speed.

Don’t get overwhelmed with a full pie.

Slice the pie up.

You won’t stress yourself out worrying about the bigger picture because you will worry about the small pieces.

It’s about mastery.

You master one small task to the best of your abilities and then you move onto the next.

This is how you build success.

Success doesn’t just happen overnight, but it happens as a collection of small successes.

Start your journey today with small baby steps.

Comment what small baby steps you will start to take towards your success.
Elements of a good story (or advertisement)
By: Josh Lee
Tags: Advertising, Storytelling, Marketing, Entrepreneurship, Copywriting

Last time I told you how powerful storytelling is.

If you can tell a good story, you can get people to do things they otherwise wouldn’t do. And that’s like having a superpower.

It can be hard to tell engaging stories. Luckily, all good stories contain some similar elements. Here they are.

Characters

Characters include both Heroes and Villains. In Marvel films, these roles are easy to spot, but in other stories they might be more difficult.

In a sales letter, the person with the problem is the Hero. The reader must have a reason to care for the Hero. The reader doesn’t have to love the character — they just need to care. If the reader doesn’t care about the Hero, the rest of your story is not going to matter.

A Villian serves as “the other.” It’s The Empire, the reason you can’t lose weight, or something else. Having a common enemy is a great way to get readers of all shapes and sizes behind a cause.

Setting

The setting includes the time and the place. When creating the setting, you want to provide enough detail so it feels real, but you still want to omit some details for the reader’s imagination to fill in.

What sounds like a better setting?

I grew up in the big city and often played with my friends.

Or

In West Philadelphia born and raised. On the playground is where I spent most of my days.

Plot

Characters and a setting are not interesting unless there is something happening. And that something is your plot.

Even though Seinfeld branded itself as “the show about nothing,” every episode included a plot and well as one or more subplots.

Jerry was always dating a new girl, George was probably getting fired, and Kramer was up to some shenanigans.

Without a plot, your characters are just sitting at home watching something on TV — probably something with a plot.

Conflict

Conflict serves as the catalyst for the story. Why does the story start now, why not before?

It also serves as a way to move the story forward. In a sales context, the conflict is usually the pain the buyer is feeling.

Resolution

The resolution is the reason why the story ends. When selling, the only way to resolve the story is to buy the product.

How do these work together?

Remember how I said these elements are found in every good story? You even find them in something as simple as a toothpaste commercial:

The Hero is you. You have teeth and you want to keep those teeth. Plaque and yellow teeth are Villians. The plot is your everyday life — living, breathing, and eating. The conflict is how food, drinks, and everything else is constantly attacking your teeth. The resolution? Buy this toothpaste to kill the Villains and end the conflict.

Next time you see an a or story, see if you can find these elements.
Today’s post was my response to a client when he asked me for LinkedIn advice.
By: Nolan Bulger
Tags: Sales, Marketing, LinkedIn, Ideas, Copywriting

Today’s post was my response to a client when he asked me for LinkedIn advice.

Photo by Greg Bulla on Unsplash

First, the one-line email: “If you have any suggestions for a LinkedIn headline I’m all ears.”

Here’s what I said:

Show some personality, be genuine; LinkedIn’s way too stiff.

Write it with your audience in mind; what’s in it for them?

Here are 7 angles you can try.

Pass the caveman test with your summary. Can someone answer these questions in 7 seconds or less?

Who’s this for?

What problem does it solve?

How can they get it?

When all else fails, find a profile you like and [ethically] copy it. Search LI for people with similar roles, click their profile and then look at “People also viewed” on the right-hand side to find examples.

Write ten versions, then run them through a headline analyzer. I shoot for a score of 70+.
My icebreaker speech
By: Carlos Henry
Tags: Self Improvement, Wealth, Relationships, Motivation, Copywriting

I joined Toastmasters.

And it was the best decision I have made besides being with my future wife because I’m marketing my personal brand while learning to public speak.

The first speech in Toastmasters is an icebreaker.

Toastmaster groups are a tight knit group and you can take advantage of this by introducing yourself to them in your first speech and networking.

Remember that your network is your net worth.

This wasn’t an in person speech, but rather a speech over a zoom call due to COVID restrictions.

I was nervous because the only time I presented in front of people was in school.

This may sound weird, but to overcome this just imagine the crowd taking a number 2.

No seriously.

Imagining everyone naked used to make me uncomfortable because I’m being stared at by naked people, but them taking a dump is just hilarious and they would be embarrassed.

I made it through my speech imagining this.

The listeners started with good praise about my enthusiasm and determination to step up and do a speech within one week of joining the group.

This has never happened.

With this being the case, they gave me more praise by telling me that I was going to be very successful.

I was going to have to get critiqued at some point.

Why not get it over with now?

I knew most of the problems I had with public speaking before the evaluator even started talking, but it sucks to hear it from someone else.

That speech was horrible.

Expectedly, the evaluator told me that I talk too fast and I always use filler words such as “uhh.”

I needed to learn to breathe.

This speech didn’t turn out as good as I thought it would be, but I did realize that speaking and writing copy are connected because you write how you speak.

Why?

Customers will connect with the copy more if it is more conversational instead of them reading an article.

Think about it.

You are persuading them to take action.

If you wouldn’t talk to them as if you were a narrator reading an article, then why would you write your copy as if it was an article?

You probably think that public speech isn’t conversational.

In a way it is.

Besides teaching you not to waste words, public speech also teaches you to talk to a mass group of people to take action by resonating with their personal emotions.

And this is why I recommend that you learn to speak in public.
Your Grandchildren will hate you if you fail to read this to the end.
Tags: Entrepreneurship, Sales, Wealth, Copywriting

Your Grandchildren will hate you if you fail to read this to the end.

Have you heard of the Igbinedions of Edo? Do you know Dangote did not come from a poor family.

They built generational wealth for themselves.

Here is your opportunity to build generational wealth for yourself and your successors.

Dan Lok who failed English twice makes.... From what I am about to show you.

What I am about to show you is the highest paid skill in the world. The skill that can make you millions if you master it.

Copywriting skill.

I like helping others. I have decided to take you hand-in-hand and walk you through the hooks and crannies of copywriting.

I will be revealing the secret of getting high paying Copywriting jobs that can make you six figures from local clients.

If you feel you are making enough money to cater for your future generation it is not for you? If you feel you feel comfortable with what you are able to achieve this year, it is not for you. If you are absolutely satisfied with your financial situation, it is not for you

I have just 14 slots left and a slot goes for just 3k.
Play FrameworkにAngular Elementsを導入してみた。
By: Takahiko Tominaga
Tags: Engineer, Angular, Scala, Play Framework, Typescript

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
[Scala] Implicit Parameter
By: Mj Park
Tags: Scala, Scala Programming

I got really confused with Scala’s implicit, so I wanted to summarize my findings and share how I learned it.

Definition

From the Tour-of-Scala tutorial, a parameter on a method can be marked as implicit, which implies that the parameter value will be taken from the context when it is called. The program will fail to compile if the implicit value is not resolved.

From the direct definitions, Scala look for implicit parameters in two different places:

Scala will first look for implicit definitions and implicit parameters that can be accessed directly (without a prefix) at the point the method with the implicit parameter block is called. Then it looks for members marked implicit in all the companion objects associated with the implicit candidate type.

Examples

This example is from here

abstract class Monoid[A] {

def add(x: A, y: A): A

def unit: A

}



object ImplicitTest {

implicit val stringMonoid: Monoid[String] = new Monoid[String] {

def add(x: String, y: String): String = x concat y

def unit: String = ""

}



implicit val intMonoid: Monoid[Int] = new Monoid[Int] {

def add(x: Int, y: Int): Int = x + y

def unit: Int = 0

}



def sum[A](xs: List[A])(implicit m: Monoid[A]): A =

if (xs.isEmpty) m.unit

else m.add(xs.head, sum(xs.tail))



def main(args: Array[String]): Unit = {

println(sum(List(1, 2, 3))) // uses intMonoid implicitly

println(sum(List("a", "b", "c"))) // uses stringMonoid implicitly

}

}

Key notes:

implicit keyword in front of stringMonoid() and intMonoid() methods indicates that the method can be used implicitly

keyword in front of and methods indicates that the method can be used implicitly in sum() , implicit parameter m means that we only need explicitly provide the first argument xs , which means the implicit parameter m needs to be implicitly defined

, implicit parameter m means that we only need explicitly provide the first argument , which means the implicit parameter m needs to be implicitly defined When sum(List(1,2,3)) is called, Scala will look for an implicit in the scope. It passes A a type Int , which means Scala will now look for an implicit of type Monoid[Int] . Therefore, the first method, intMonoid is used

is called, Scala will look for an implicit in the scope. It passes a type , which means Scala will now look for an implicit of type . Therefore, the first method, is used Also, when sum(List(1,2,3)) is called, note that intMonoid can be accessed directly, therefore passed automatically

Scala will first look for implicit definitions and implicit parameters that can be accessed directly (without a prefix) at the point the method with the implicit parameter block is called.

Conclusion

Yes.. it is very confusing, and I still do not fully understand the details. I will update the post as I acquired deeper knowledge. Thanks for reading all!
[Scala] “Lazy” val in Scala
By: Mj Park
Tags: Scala, Scala Programming

[Scala] “Lazy” val in Scala

What is the keyword “lazy” in Scala, and how is it being used? Any pitfall we can get from it? Let’s explore.

What is “lazy” val?

When declared in front of val , the compiler will not immediately evaluate the expression, but it will evaluate the bound expression at its first access. In a subsequent access, it will just return the result without any further execution or calculation.

def fib(n: Int): Int {

// fib() is a method that calculates a fib number

} object ValStore {

lazy val fortyFive = fib(45)

lazy val fortiySix = fib(46)

}

Pitfalls of “lazy”

During an evaluation of a lazy val, the whole instance is locked, which means when different lazy vals are accessed from multiple threads, the calculation on them will need to happen sequentially.

In the above case, there are two lazy vals in ValStore singleton. If we try to access them from different threads, the one needs to wait until the first execution is done.

In the below example, when the first initialization (4) executes a calculation on the lazy val fortyFive (1), another initialization (5) cannot execute a calculation on another lazy val fortySix (2) because the whole instance ValStore is locked until the first initialization is done

object ValStore {

lazy val fortyFive = fib(45) // (1)

lazy val fortySix = fib(46) // (2)

} object Scenario1 {

def run = {

val result = Future.sequence(Seq( // (3)

Future {

println("starting (45)")

ValStore.fortyFive // (4)

println("done (45)")

},

Future {

println("starting (46)")

ValStore.fortySix // (5)

println("done (46)")

}

))

Await.result(result, 1.minute)

}

}

Conclusion

I explored some basics of lazy in Scala. More examples will come as I acquire deeper knowledge on this!
- Sarath Kallatt Sivasankaran
By: Sarath Kallatt Sivasankaran
Tags: Functional Programming, Scala, Scala Programming

Another way of implementing fizzBuzz is with flatMap and mkString
New Scala 3 (Dotty) Features in an Example Web Application
By: Pawel L.
Tags: Programming, Web Applications, Scala 3, Scala, Functional Programming

The application is started with sbt "run <port number>" command and accepts the requests. For example when it gets the request below (port 9000 given at the start):

Example request.

The user will get the JSON response:

Example response.

The flow:

The requests are accepted by AkkaHttp server in Server class.

class. The proper method of StarSystemService is called. For a full information set about the celestial body it is getFullData , for the environment only getEnvironment .

is called. For a full information set about the celestial body it is , for the environment only . A simple validation is performed (just to have an error response opportunity).

The requested body information is obtained from StarSystemRepository .

. The response is built and returned to Server .

. JSONEncoder instance is used to build the final HTTP response.

Scala 3 features

Givens

One of the biggest changes introduced in Scala 3 is replacement of implicits with the new mechanism. If somebody used implicits in Scala 2 probably knows that they are great when they work, but if something stops compiling, it can be hell to deal with it.

The new approach was designed to overcome their drawback and create a more transparent mechanism. I’ll not describe it in deep, but in the context of the application (a large topic good for a new article or two, I recommend the reference — the link below).

In a nutshell, we can define now a given (Scala 2 implicit value, class or function) that can be bound to a context parameter defined with using (Scala 2 implicit method parameter) keyword or with context bounds. See the code snippets below to see how it works.

A simple monad is used by the program:

LittleMonad type class.

There are used givens to create monad instances. In the regular program flow the instance for Future is used:

LittleMonad instance for Future type.

In this case an anonymous given is created (though the compiler will generate one). This given also uses other one — ExecutionContext . In this case it is Scala 2 implicit — that can cooperate with the new feature.

A nice feature of givens is that we can request to use them by type and ignore the name (usually the name of Scala 2 implicit doesn’t matter, it is defined because of the syntax requirement).

We can also set a name ( futureInstance ) and use it later while referring to the given:

Named given.

For unit tests an instance for Id is used. Id type (you may know it if you use Cats or Scalaz library) is defined here as:

The Id monad instance doesn’t need any dependencies:
This week in #Scala (Dec 14, 2020)
By: Petr Zapletal
Tags: Scala, Zio, Thisweekinscala, Functional Programming, Akka

This week in #Scala (Dec 14, 2020)

This blog aims to keep you up to date with the latest news from the world of Scala and Reactive programming.

It has been a week since the previous #ThisWeekInScala so let’s catch up on the latest Scala & Reactive happenings…

New Content

Releases

The Weaver Test is out!

New zmail available

IntelliJ Scala Plugin 2020.3 Is Out!

In case you are looking for new challenges, pay attention, because Disney Streaming Services is hiring!
Variable Evaluation Rules in Scala
By: Sudarshan Kasar
Tags: Lazy Val, Scala, Call By Value, Call By Name

def x = 2 //evaluated when called

val y = 2 //evaluated immediately

lazy val z = 2 //evaluated once when needed

def callByValue(x: Int)// Evaluates the funtion argument(x)’s before calling the function

def callByName(x: => Double)// Evaluates the funtion then evaluates funtion argument(x)s if needed

object EvaluationRulesScala {

def main(args: Array[String]): Unit = {

//valVarDeclaration 2

println(“****starting the app***”) // ****starting the app***

val defVarDeclarationCall1 = defVarDeclaration // defVarDeclaration 1

val defVarDeclarationCall2 = defVarDeclaration // defVarDeclaration 1

val valVarDeclarationCall1 = valVarDeclaration //

val valVarDeclarationCall2 = valVarDeclaration //

val lazyValVarDeclarationCall1 = lazyValVarDeclaration // lazyValVarDeclaration 3

val lazyValVarDeclarationCall2 = lazyValVarDeclaration //

callByValue({

println(“passing the value “+ 10)

10

}) // passing the value 10

// call by value example

// 10

callByName({

println(“passing the value “+ 20)

20

}) // call by name example

// passing the value 20

// 20

}

def defVarDeclaration = {

println(“defVarDeclaration “ + 1)

1

}

val valVarDeclaration = {

println(“valVarDeclaration “ + 2)

2

}

lazy val lazyValVarDeclaration = {

println(“lazyValVarDeclaration “ + 3)

3

}

def callByValue(x: Int): Unit = {

println(“call by value example “)

println(x)

}

def callByName(x: => Int): Unit = {

println(“call by name example “)

println(x)

}

}
airframe-log for Scala 3 (Dotty)
By: Taro L. Saito
Tags: Dotty, Scala, Logging, Airframe

Photo by Aaron Burden on Unsplash

Airframe Log, a modern logging library for Scala, now supports Scala 3.0.0-M2 (Dotty) since version 20.12.1, released on December 2020.

The usage is quite simple: Add LogSupport trait to your class and use error/warn/info/debug/trace methods for showing logs of your applications:

Now your application can show colorful logs, enriched with the source code location:

airframe-log uses Scala macros to reduce the overhead of generating log messages if the corresponding log level is not enabled. The biggest challenge in supporting Scala 3 was adopting the brand-new Scala Macro for Scala 3 while maintaining compatibilities with Scala 2.13 and Scala 2.12. To do so, we split the source code for Scala 2 and 3. The transition from Scala 2 to 3 may take several years until various libraries that are using Scala 2 macros or runtime-reflections will be fully migrated to Scala 3. Now, airframe-log has joined the list of libraries supporting Scala 3!

We still have many modules that need to be migrated to Scala 3, but now that tooling like sbt 1.4.x, vscode, and IntelliJ gradually have started supporting Scala 3 builds, it would be good timing to try and learn new exciting features of Scala 3!
A Parametric Top Type?
By: Mark, Justin
Tags: Scala, Dotty

I haven’t been writing much here lately (mostly because I’ve been very busy with my day job), but there’s a really interesting conversation going on right now in the Dotty repo.

It’s well worth reading the thread if you are interested in the fine details of Scala, and especially if you care about the type system. The high concept is to make the language more precise and correct by introducing a Top type above Any , or possibly modifying Any , or other possibilities — it’s a deep discussion, and pretty fascinating.
Feedback sought on Optional Braces
By: Mark, Justin
Tags: Scala, Dotty

Readers here know that I’m not entirely a fan of Scala 3’s optional-braces feature. (I don’t entirely despise it, but I don’t like it, and personally I think it’s been pushed too hard in the leadup to 3.0.)

Anyway, Martin has opened a discussion around it on the Contributors Forum. Folks who have thoughts should give that a read, and consider chiming in. (I’m still gathering my own thoughts.)

One meta-comment around that — this issue has raised a lot of passions, and discussions about it have recently become excessively heated. So please, keep it civil: a frank discussion of the pros and cons are in order, but flamewars aren’t. Thanks!
Scala — companion objects. In scala , companion object is an…
By: Kumar Ramanathan
Tags: Companion Object, Scala

In scala , companion object is an object with same name as class name.

example:

class employee {

}

object employee{

}

companion object and class will share its private members .

example

class employee {

def display = { println (“this is demo of access private”+securityname)}

}

object employee{

private val securityname = “secret”

}

apply method makes to create object with out newkey word , should be defined in object. apply is basically a constructor like thing , we can have more than one apply method to have multiple constructors concept.

example

class employee{

var name:option[String] =None

var age:option[Int]=None

override def toString= s “$name , $age”

}

object employee{

def apply(name:option[String]):employee = {

var s = new employee

s.name = name

s

}

def apply(name:option[String]):employee = {

var y = new employee

y.name=name

y.age=age

y

}

}

val employeeData = List(employee.apply(“sam”),employee(“ram”,22))

here we can call with apply method or with out apply method. if companion object doesnot have apply method and we create instance with new method , the compiler will throw error.
That’s a very good point!
By: Alexey Soshin
Tags: Scala

That’s a very good point!

We didn’t have such a problem, our monorepo was in Scala, and it’s nearly impossible to find freelance Scala developers in the first place 😂
What’s New in Scala 3?
By: Akash Srivastava
Tags: Programming, Scala, Functional Programming, Software Engineering, Software Development

New Ways to Manipulate Types!

Scala 3 gives us a much richer toolkit for describing data by letting us define types in a much more descriptive way. Let's have a look at some of the new types introduced.

Types can now be defined as a union of other types, and they don’t necessarily have to share a common base class. Let’s understand this with a simple use case: You have to buy a new smartphone, and the reason you choose one can be either its camera, processor, or operating system. Let's take a look at how we can cook this up in Scala 3.

Scala 3 also have intersection types now. To put it simply, if we think of the union of types as either A or B , then intersection can be thought of as both A and B . Here’s an example:

Literal types

We can now literally define any literal value as a type with a singleton instance of itself. Simply put, a literal value like ABC , 2.7 , and true can now be treated as a type in itself. Let’s understand this with an example:

This one is particularly useful when we are working with domain-driven design, and we often have to define new types as wrappers over other types. For example, we may define a type called ItemID which is actually just a wrapper over the String type with a restriction that the first character needs to be in uppercase.

The problem with using wrapper types for this is that we incur unwanted overhead when accessing their fields or methods, or composing these types. And these overheads start to add up if we have a lot of such entities in our design.
Monad transformers and cats. Monad transformers implemented in cats…
By: Krzysztof Atłasik
Tags: Cats, Scala, Monad Transformers, Monads, Functional Programming

Monad transformers and cats

Monad transformers implemented in cats provide rich API allowing great flexibility in the way we shape our applications.

The downside of such powerful API is, that sometimes it might be not an easy task to grasp all the correct uses. It is especially true if you’re new into functional Scala.

So, I thought it would be helpful to share some tips.

My blog post is not meant to explain monad transformers from scratch. I assume you already know basics and if not, you can check this great article.

We will be dealing with arguably the two most popular monad transformers: OptionT and EitherT.

Tip 1. Use the right factory method

The main purpose of monad transformers is altering nested monad stack like IO[Option[A]] to a single monad data type like OptionT[A] .

Stack IO[Option[A]] might describe a computation that performs side-effect returning a single value that might or might not exists. A good example might be a query to the database to get the user by its id:

def getUserById(id: UserId): IO[Option[User]]

We could use OptionT.apply to transform result returned by the method into OptionT and then compose it with other methods with similar signature:

The problem is that in real life not all methods in our application will look like this. For example, we could deal with methods performing database queries but always returning a result (we’re ignoring network issues for now):

def getUsers(): IO[List[User]]

Another case is a pure method that takes some value and then optionally returns the result:

def validateUser(user: User): Option[ValidatedUser]

It’s not all. Some methods could return a plain value, another could return stacked IO and Either and so on.
Diving into Scala Cats — Monoids. Today we are going to deep dive into…
By: Mansi Babbar
Tags: Monoids, Scala Cat, Scala, Functional Programming, Semigroup

Today we are going to deep dive into the Scala Cats again to find out about Monoids. If you haven’t already read my post about Diving into Scala Cats — Semigroups I suggest you do so now.

What are Monoids?

The Monoid extends Semigroup and adds a default or fallback value for the given type. Monoid type class comes with two methods - one is the combine method of Semigroups, and another one is the empty method that performs identity operation.

In the post about Semigroups, we saw an example where we’re using Semigroups along with Scala’s fold() to operate on a collection of values:

def combineStrings(collection: Seq[String]): String = {

collection.foldLeft("")(Semigroup[String].combine)

}

We discussed the limitation of Semigroups where we cannot write a generic method combineAll(collection: Seq[A]): [A] for the above expression because the fallback value will depend on the type of A ( ”” for String , 0 for Int , etc).

Monoid comes up with a solution to this shortcoming, by introducing an identity/empty element.

The signature of Monoid can be specified as:

trait Monoid[A] extends Semigroup[A] {

def empty: A

}

How does identity element solves the limitation of Semigroups?

The empty String that we are passing in combineStrings is known as the identity or empty value, we can think of it as a fallback or default value. It resolves the shortcoming of Semigroups.

Now we can easily provide the implementation of generic method combineAll(collection: Seq[A]): [A] using Monoids:

def combineAll[A](collection: Seq[A])(implicit ev: Monoid[A]): A = {

val monoid = Monoid[A]

collection.foldLeft(monoid.empty)(monoid.combine)

}

Monoid holds Associativity and Identity Laws

Since Semigroups follow principle of associativity, same rules with some add-ons are applied to Monoids as well.

combine operation has to be associative and empty value should be an identity for the combine operation:

combine(x, empty) = combine(empty, x) = x

For example:

// Integer addition using 0 as an identity (Rules valid)

1 + 0 == 0 + 1 == 1 // Integer multiplication using 1 as an identity (Rules valid)

2 * 1 == 1 * 2 == 2 // Integer multiplication using 0 as an identity (Rules invalid)

2 * 0 == 0 * 2 != 2

So it’s clear the empty /identity element depends on the context not just on the type. That’s why Monoid (and Semigroup ) implementations are specific not only to the type but also the combine operation.

Cats allows combining Monoids together to form bigger Monoids and write more generalized functions which will take something composable instead of some concrete types.

We’ll learn about more core concepts of Cats in our upcoming article.

Stay tuned!!!

References

The best two Scala Cats resources I know are here:
Diving into Scala Cats — Monoids
By: Knoldus Inc.
Tags: Monoids, Scala Cats, Scalafp, Scala, Functional Programing

Today we are going to deep dive into the Scala Cats again to find out about Monoids. If you haven’t already read my post about Diving into Scala Cats — Semigroups I suggest you do so now.

What are Monoids?

The Monoid extends Semigroup and adds a default or fallback value for the given type. Monoid type class comes with two methods - one is the combine method of Semigroups, and another one is the empty method that performs identity operation.

In the post about Semigroups, we saw an example where we’re using Semigroups along with Scala’s fold() to operate on a collection of values:

def combineStrings(collection: Seq[String]): String = {

collection.foldLeft("")(Semigroup[String].combine)

}

We discussed the limitation of Semigroups where we cannot write a generic method combineAll(collection: Seq[A]): [A] for the above expression because the fallback value will depend on the type of A ( ”” for String , 0 for Int , etc).

Monoid comes up with a solution to this shortcoming, by introducing an identity/empty element.

The signature of Monoid can be specified as:

trait Monoid[A] extends Semigroup[A] {

def empty: A

}

How does identity element solves the limitation of Semigroups?

The empty String that we are passing in combineStrings is known as the identity or empty value, we can think of it as a fallback or default value. It resolves the shortcoming of Semigroups.

Now we can easily provide the implementation of generic method combineAll(collection: Seq[A]): [A] using Monoids:

def combineAll[A](collection: Seq[A])(implicit ev: Monoid[A]): A = {

val monoid = Monoid[A]

collection.foldLeft(monoid.empty)(monoid.combine)

}

Monoids hold Associativity and Identity Laws

Since Semigroups follow principle of associativity, same rules with some add-ons are applied to Monoids as well.

combine operation has to be associative and empty value should be an identity for the combine operation:

combine(x, empty) = combine(empty, x) = x

For example:

// Integer addition using 0 as an identity (Rules valid)

1 + 0 == 0 + 1 == 1



// Integer multiplication using 1 as an identity (Rules valid)

2 * 1 == 1 * 2 == 2



// Integer multiplication using 0 as an identity (Rules invalid)

2 * 0 == 0 * 2 != 2

So it’s clear the empty /identity element depends on the context not just on the type. That’s why Monoid (and Semigroup ) implementations are specific not only to the type but also the combine operation.

Cats allows combining Monoids together to form bigger Monoids and write more generalized functions which will take something composable instead of some concrete types.

We’ll learn about more core concepts of Cats in our upcoming article.

Stay tuned!!!

References

The best two Scala Cats resources I know are here:
Scala : No More Looping
By: Neel Desai
Tags: Java, Functional Programming, Scala, Scala Programming

This blog is more targeted to the Scala beginners. Scala is a functional programming language, to be clear it is EXPRESSIONS kind of language while language like Java is more imperative programming language. It is more kind of creating instructions/tasks for a program. Let me explain this concept with example of loops.

Java has a concept of loops.Like for , while . In Scala, creating while loops is considered as a bad practice.

For an example, look at the following code snippet

var a = 42 while(a < 100) {

println("Hey, I am in a loop")

a += 1

}

This way of writing a while loop, is an imperative way (Instructions like in JAVA).

In Scala, we try to think everything functionally. Rather than thinking like, how to loop over a collection, try to think like How you can transform a collection that you are looking for. For example, let me rewrite the above while loop more functional way

(42 until 100).foreach(_ => println("Hey, I am now looping correctly"))

Let me give more example of how to transform a collection in scala

List(1,2,3).map(_ * 2) // List(2,4,6)

List(1,2,3).flatMap(x => List(x, x+1) // List(1,2,2,3,3,4)

List(1,2,3,4).filter( _ % 2 ==0 ) // List(2,4)

In above example, I am transforming my collection to what I want using Higher Order Functions. There are few more functions like fold, sum, reduce, find, count

Conclusion:
Scala: Case Classes
By: Micah Lewis
Tags: Coding, Class, Scala, Case Class

Sorry, considering the other blog posts I did on apply and unapply as well as companion objects, this one regarding case classes seems a bit out of order. Nevertheless, we should talk about case classes which are special to Scala. Case classes bring class instantiation [creation] and definition into the modern world. Consider the following code:

class Book(isbn: String) {

def apply(isbn: String) = {

val b = new Book

b.isbn = isbn

b

} def unapply(b: Book): String = s"${b.isbn}"

} val frankenstein = new Book("978-0486282114")

This is how we would normally would define a class for a new book, say Frakenstein. Now take a look at the same code using the power of Scala’s case class

case class Book(isbn: String) val frankenstein = Book("978-0486282114")

Muuuuuuuuch easier. Take a look at the two bits of code and think about what the difference are. Below is a list of differences between case classes and regular classes in Scala

Case class do not need to have an apply and unapply method. They are created behind the scenes in its companion object.

Because of this, the case class does not need the “new” keyword when instantiating [creating] a new instance of the class. [As of writing, I don’t know why this is. If you know, please help me out and let me know in the comments below]

All of the values created defined within a case class are public val and cannot be changed. If you want to change the value of a value in a class, the case classes have a very handy .copy method for handling this:

case class Message(sender: String, recipient: String)



val message1 = Message("micah", "artem")

val message2 = message1.copy //creates a shallow copy of message1 val message3 = message1.copy(sender = "richard")

Case classes also have some other handy built-in functions that you might find useful, for example .toString which, you probably guessed it, converts what you put before it into a string.

which, you probably guessed it, converts what you put before it into a string. Case classes also can be used in equality statements for example, take a follow up to the code above:

message1 == message2 //returns true

Well, let’s keep this from dragging on, and wrap up here. Again if you spotted any mistakes, have any questions, or anything to add, please let me know in the comments below! Thanks for reading!
Do we really?
By: Miłosz Tadrzak
Tags: Java, Kotlin, Scala

Do we really? I think that you should provide some arguments for why one should use Kotlin when Java is there.

The only one that comes to my mind when I try to reason Kotlin over Scala is ”mobile development” aspect. But for example then I think about Data Engineering I think “Scala”.

What’s more when I reason Scala over Java I know why I choose Scala. Tell me why should I consider Kotlin?

Here’s a nice article form professionals that use Scala almost everywhere: https://scalac.io/why-does-scala-win-against-kotlin-senior-engineers-opinion/
Fun with Akka Actor System
By: Diego Pacheco
Tags: Typesystem, Sbt, Scala, Fp, Akka

Akka is a kick as technology. Today I want to share a video I made about how we can model an actor system using Akka, Scala, SBT, and IntelliJ Idea. We will model a vending machine using Akka and Scala. We will take advantage of the Scala Type system and Akka typed actors. Type Systems are great because they make programming more secure and prevent bugs and require less testing since the compiler does more for you. For this video, we also will be using SBT 1.4.0, Scala 2.13, and Akka 2.6. So I hope you guys like it. So let’s get started!

The video

The Code

Cheers,

Diego Pacheco
Scala: Handy implicit
By: Niroj Pattnaik
Tags: Scala Implicits, Camel Case, Resultset, Scala, Generics

Whenever I get a chance to work in Scala, I always love its simplicity like Python, handiness like Perl, and running like Java.

Scala’s implicit ways are another way of writing syntactical sugary flavors of writing compact code in your own style which makes it easier to call from external class or code blocks. Here, I’m keeping a few custom definitions I use frequently:

I. CamelCase :

A camel case implicit function can be handy while storing strings like First & Last Name. It can be also easily called from Spark using a UDF as shown below:

scala> "niroj pattnaik".toCamelCase

val res21: String = Niroj Pattnaik scala> "niroj K pattnaik".toCamelCase

val res22: String = Niroj K Pattnaik

II. Database Result Conversion:

Calling a DB resultset object from an external class not only looks ugly but also keeps the responsibility on the user to loop through the result set and do the conversions. Here I’m trying to help the fellow users to call it externally in an easier way:

val colValue = ExecuteDbQuery.as[Long](configFilePath = "db2.config", query = s"SELECT col FROM TABLE" )(0)(0) val result = ExecuteDbQuery.as[Any](configFilePath = "db2.config", query = s"SELECT col1,col2 FROM TABLE" )

val col1Value = result(0)(0).parse(Long)

val col2Value = result(0)(1).parse(Int)

III. Easy Sequence Differentiations:

Here I’m overriding the minus(“-”) sign to find an iterable object like a Sequence object. The data type is kept generic type [A] here:

scala> Seq("A", "B") - Seq("A")

val res24: Seq[String] = List(B) scala> Seq(1, "B") - Seq("A")

val res25: Seq[Any] = List(1, B)

Hope you like it. Implicit function makes the Scala code more readable like shown in the above few examples. I will keep on adding such new implicit functions whenever time permits in these sections.

Thank you for reading. Please like and comment if you find it helpful.
Introduction to ScalaTag
By: Emmett Kyoon Na
Tags: Scalatags, Intoduction, Scala, Http4s, Scalajs

4. Example with Http4s

Http4s is one of the most popular http server along with Akka Backend in Scala world. (https: 1.9K ⭐s, Akka-http: 1.1K ⭐s on Github)

It’s got plenty of reference and users. Moreover, it supports ScalaTags when it comes to integration.

This is a route file

import cats.effect.Sync

import org.http4s.HttpRoutes

import org.http4s.dsl.Http4sDsl

import org.http4s.scalatags._

import scalatags.Text.all._

import scalatags.Text.tags2.{title => mainTitle}

object ScalatagsRoutes {

def helloWorldRoutes[F[_]: Sync]: HttpRoutes[F] = {

val dsl = new Http4sDsl[F]{}

import dsl._

HttpRoutes.of[F] {

case GET -> Root =>

val helloWorldInScalaTags =

html(

mainTitle("ScalaTags Playground"),

body(h1("Hello World!"))

)

Ok(helloWorldInScalaTags)

}

}

}

The base project is generated by sbt seed sbt new http4s/http4s.g8

As you can see, simple tags do all the jobs. entire codes can be found here, emmett/scalatags-example
Guys, please stop comparing Scala with Java.
By: Are Husby
Tags: Java, Kotlin, Scala, Programming Languages

Guys, please stop comparing Scala with Java. The Java crowd is looking towards Kotlin now. You need to explain why one should use Scala now that Kotlin is here.
Développeur·se Backend API
By: Annabel Vincent
Tags: Hiring, Backend Developer, Scala, Join Us

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Développeur·se Backend Data
By: Annabel Vincent
Tags: Montpellier, Scala, Data, Join Us

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
If else condition in spark Scala Dataframe
By: Parmanand Kumar
Tags: Sql Case When, When Function In Spark, When Multiple Conditions, Scala, Spark

If else condition in spark Scala Dataframe

In SQL world, very often we write case when statement to deal with conditions. Spark also provides “when function” to deal with multiple conditions.

In this article, will talk about following:

when when otherwise when with multiple conditions

Let’s get started !

Let’s consider an example, Below is a spark Dataframe which contains four columns. Now task is to create “Description” column based on Status.

import org.apache.spark.sql.{DataFrame, SparkSession}

import org.apache.spark.sql.functions._ object CaseStatement { def main(args: Array[String]): Unit = {

val sparkSession = SparkSession.builder

.appName("TestAPP").master("local[2]").getOrCreate()

val tempDF:DataFrame=sparkSession.read.option("header","true")

.option("delimiter",",").csv("Data/weblog.csv")



/*

Case statement

*/

val finalDF=tempDF.withColumn("desc",



when(col("Status")===200,"Success")

.when(col("Status")===404,"Not found").

otherwise(lit("Unknown"))

)



finalDF.show(5);

}



}

Output :

As it can be noticed that one extra “desc” column got added. And status 200 has success as descriptions.

Please visit spark-tutorial for beginner to learn spark from scratch !

Thanks for reading!

Please do share the article, if you liked it. Any comments or suggestions are welcome.

Don’t forget to follow me !
Scala 3: Contextual Abstractions, Part III
By: Dean Wampler
Tags: Programming Scala, Scala, Scala 3

5 Seconds, © 2020, Dean Wampler. All Rights Reserved.

In my last post, before the revolution, I discussed the Scala 3 way of defining type classes.

Update, November 18, 2020: I added new information about importing given instances. Update: December 27, 2020. The syntax for given instances and extension methods was refined slightly in Scala 3.0.0-M3.

This post finishes this quick overview of contextual abstractions with a discussion of the new using clauses that replace implicit parameter lists.

But first, Scala 3 reached its first milestone release this past week, Scala 3.0.0-M1 . The book examples now use it. The Scala team hopes to have the first release candidate ready by Christmas.

Consider the following contrived example that wraps sequences with a sorting functionality. Never mind that sequences already provide this ability, which the implementation actually uses.

Several ways to define implicits and using clauses

The first method, sortByImplicits , uses a Scala 2 implicit parameter list. This is still supported in Scala 3, but will be deprecated eventually. Note that the ordering instance o is passed explicitly to Seq.sortBy .

The second and third methods, sortBy1a and sortBy1b , show the new using clause syntax. The first one just replaces the keyword implicit with using , while the second shows that you can leave the value anonymous. In this case, the new summon method is used to bind the anonymous instance. In fact, I only need this because I’m passing the instance explicitly, but of course I wanted to show you the new way of binding an instance when needed. In fact, summon is identical to the Scala 2 method implicitly , but with a new name.

Finally, sortBy2 shows the context bound syntax for writing the same thing. This syntax is the same as for Scala 2, but now it’s a shorthand way of writing using clauses.

Let’s try it:

The given evenOdd ordering returns even numbers first, then odds, sorted descending. The comment shows an alternative way of defining the given instance, using the syntax discussed in the previous post.

The two groups of assert statements use the given instance implicitly, then explicitly.

If the given instance is anonymous, you can bind it using summon , which behaves exactly like the previous method for this purpose, implicitly . (A new name for a rebranded concept.)

Importing Given Instances

We all like the convenience of using wild-card imports, like import foo.bar._ , but we might prefer more control over given instances and older implicit definitions. Scala 3 introduces a new syntax for this purpose:

The comments describe the import behaviors. In Scala 3.0, _ will still import everything, for backwards compatibility, but Scala 3.1 will begin transitioning to the specific behavior described in the comments. You can also force the compiler to use the 3.1 behavior now by adding the -source:3.1 or similar flags.

What’s Next?

In the next several posts, I’ll explore changes in the type system.