Monday, February 27, 2012

Having Fun with Monoid in Scalaz Seven

It's been some times since my last blog on Scalaz Seven that talks about Functor. You may have guessed that my second post on the series would be Applicative Functor. Well, sorry, I can't write in order yet, I prefer to talk about Monoid in Scalaz Seven instead. OK Let's have fun.

Having Fun With |+|
To start with, let's have some fun with |+| operator.

Let's start

scala> 6 |+| 7
res0: Int = 13

Well, not that interesting. It's just an addition. What about

scala> 6 + "9"
res2: String = 69

scala> 6 |+| "9"
<console>:14: error: type mismatch;
 found   : java.lang.String("9")
 required: Int
       6 |+| "9"

Not bad. |+| somehow protects you from adding integer to String. OK, not bad, but, not that fun. What about this:


scala> some(6) |+| some(9)
res9: Option[Int] = Some(15)

All right, that starts to be interesting. Give me more:

scala> some(6) |+| some(9) |+| some(10)
res10: Option[Int] = Some(25)


scala> some(6) |+| some(9) |+| some(10) |+| none[Int] |+| some(6)
res11: Option[Int] = Some(31)

Not bad at all. Want something more than that. Some String ?

scala> "Hello" |+| "World"

res25: java.lang.String = HelloWorld

scala> some("Hello") |+| some("World")

res26: java.lang.String = Some(HelloWorld)


What else do you have ? List ?


scala> List(2,4) |+| List(4, 5)
res28: List[Int] = List(2, 4, 4,5)

Cool. Boolean?


scala> val b = true
b: Boolean = true


scala> val c = true
c: Boolean = true


scala> b |+| c
<console>:24: error: value |+| is not a member of Boolean
       b |+| c
         ^

Ouch. Why ? Well, because |+| can be interpreted in conjunction or disjunction (note that, actually this works in Scalaz 6, not sure if scalaz seven will make it work as in scalaz 6). To fix this, let's do the following:


scala> val a = Conjunction(true)
a: scalaz.package.@@[Boolean,scalaz.Tags.Conjunction] = true


scala> val b = Conjunction(true)
b: scalaz.package.@@[Boolean,scalaz.Tags.Conjunction] = true


scala> val c = Conjunction(false)
c: scalaz.package.@@[Boolean,scalaz.Tags.Conjunction] = false


scala> a |+| b
res34: scalaz.package.@@[Boolean,scalaz.Tags.Conjunction] = true


scala> a |+| c
res35: scalaz.package.@@[Boolean,scalaz.Tags.Conjunction] = false


scala> a |+| b |+| c
res36: scalaz.package.@@[Boolean,scalaz.Tags.Conjunction] = false

All right. That makes sense. What about Disjunction ? Well, just do the same.

scala> val e = Disjunction(true)
e: scalaz.package.@@[Boolean,scalaz.Tags.Disjunction] = true


scala> val f = Disjunction(true)
f: scalaz.package.@@[Boolean,scalaz.Tags.Disjunction] = true


scala> val g = Disjunction(false)
g: scalaz.package.@@[Boolean,scalaz.Tags.Disjunction] = false


scala> val h = Disjunction(false)
h: scalaz.package.@@[Boolean,scalaz.Tags.Disjunction] = false


scala> e |+| f
res37: scalaz.package.@@[Boolean,scalaz.Tags.Disjunction] = true


scala> e |+| h
res38: scalaz.package.@@[Boolean,scalaz.Tags.Disjunction] = true


scala> g |+| h
res39: scalaz.package.@@[Boolean,scalaz.Tags.Disjunction] = false

OK. That's cool, but it starts to be boring. Doesn't it? Give me something more spectacular.  What about Tuple?  All right, what about Tuple?

scala> (6, "Hello", List(4, 2)) |+| (7, "Hello", List(5))
res40: (Int, java.lang.String, List[Int]) = (13,HelloHello,List(4, 2, 5))

So, |+| actually "sums" each corresponding element of two tuples. That's quite cool. What if they are nested? Will it work ?

scala> (some(6), some("Hello"), (some(5), some(3))) |+| 
        (some(7), none[String], (some(6), none[Int]))

res43: (Option[Int], Option[java.lang.String], (Option[Int], Option[Int])) = 

(Some(13),Some(Hello),(Some(11), Some(3)))


Fantastic! Pretty cool.

[ I heard somebody there "you see, this Scalaz guy loves using funny operator. This time, they use |+|. OMG, That's not readable". All right, all right. You can actually change all |+| above with its alias called mappend, hope you're happier now].

Monoid and Semigroup Behind the Scene


Behind the scene, what happen is that Scalaz offers a quite simple but powerful abstraction, called Monoid. Believe me, Monoid is something quite simple: it's a type class with two functions: append and zero: 


1     
2      trait Monoid[A] { 
3        val zero: A 
4        def append(s1 : A, s2 : => A):A
5      } 


With the following contract (or a law, if you wish)


zero append x = x
x append zero = x
(x append y) append z = x append (y append z)


Scalaz provides several instances of Monoid (we have seen some of them in action above):

  • Int, Short, BigInt, BigDecimal, Byte, Short ...
  • Boolean conjunction and disjunction
  • List and Stream
  • String
  • Either.LeftProjection and Either.RightProjection.
  • ...
What about Option and Tuple ? Actually, Scalaz also provides some derived Monoid, like:
  • Option[A] is a monoid if A is monoid 
  • Tuple[A, B, C, D] is a monoid if A, B, C, and D is monoid
  • Map [A,B] is a monoid if B is a monoid
  • ...
Map is an interesting example. Let's try this:

scala> val m = Map("UO" -> BigDecimal(40.2),
     |              "US" -> BigDecimal(50.1),
     |              "YR" -> BigDecimal(10.1))
scala> val n = Map("UO" -> BigDecimal(10.2),
     |              "US" -> BigDecimal(40.0),
     |              "YZ" -> BigDecimal(10.5))
scala> m |+| n
res47: scala.collection.immutable.Map[java.lang.String,scala.math.BigDecimal] = Map(UO -> 50.4, US -
> 90.1, YZ -> 10.5, YR -> 10.1)

As you can see, |+| adds every corresponding element in m and n. If there's no corresponding element, for example "YR" in m and "YZ" in n, then it just puts the element in the result map.

All examples so far use append function of Monoid, but not zero. A type class with only append is called Semigroup. The function zero is useful when we want to fold a list of monoid, for example using suml function also provided by scalaz:

scala> val xs = List(some(2,4), some(1, 3), some(2, 10))
xs: List[Option[(Int, Int)]] = List(Some((2,4)), Some((1,3)), Some((2,10)))

scala> xs.suml
res48: Option[(Int, Int)] = Some((5,17))


Conclusion
Scalaz provides a cool thing called Semigroup and Monoid. With that, we can benefit the operator |+| and sum for their instances like Integer, String, List, and so on. But the main benefit is that Scalaz provides implementation of Monoid for Option, Tuple, and Map. You don't need to know what Monoid or Semigroup are to benefit all this. But, why should you avoid them ? It's a very simple stuff.

I hope you enjoy this very express introduction to Scalaz Seven Monoid. Who said Scalaz is complex ?
 I'm preparing more on this subject. So, stay tuned.


51 comments:

deeksha said...



this blog is really amazing and it is really very interesting and tremendous thanks for sharing those valuable information.

php Training in Chennai

Unknown said...

It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command .

Branding Services in Chennai

Varshaa said...


What an awesome post, I just read it from start to end. Learned something new after a long time.


Car Cleaning Services in Mumbai


back to original car services

Unknown said...

The blog gave me idea about components of hadoop.They explained in effective manner.Thanks for sharing it. Keep sharing more blogs.

Bigdata Training in Chennai

ram said...

This is a terrific article, and that I would really like additional info if you have got any. I’m fascinated with this subject and your post has been one among the simplest I actually have read.
Data Science training in rajaji nagar | Data Science Training in Bangalore
Data Science with Python training in chennai
Data Science training in electronic city
Data Science training in USA
Data science training in pune

cathryn said...

This is good site and nice point of view.I learnt lots of useful information.

angularjs-Training in pune

angularjs Training in bangalore

angularjs Training in bangalore

angularjs Training in chennai

automation anywhere online Training

angularjs interview questions and answers

Kayal said...

This content is very good way for devolep the knowledge. Thanks for your wonderful post. I would like to regular updates from your blog...
IELTS coaching in Chennai
IELTS Training in Chennai
IELTS coaching centre in Chennai
Best IELTS coaching in Chennai
IELTS classes in Chennai

Kayal said...

This content is very good way for devolep the knowledge. Thanks for your wonderful post. I would like to regular updates from your blog...
IELTS coaching in Chennai
IELTS Training in Chennai
IELTS coaching centre in Chennai
Best IELTS coaching in Chennai
IELTS classes in Chennai

Suba said...


This could be one of the most useful blogs I have ever come across on this technology. I am a newbie to this technology. Great work admin.
Software testing training in chennai
Salesforce Training in Chennai
Big Data Training in Chennai
Hadoop Training in Chennai
Android Training in Chennai
Selenium Training in Chennai
Digital Marketing Training in Chennai
JAVA Training in Chennai
big data training and placement in chennai

jefrin said...

Nice to read this blog
salesforce training institute chennai

jefrin said...

Very impressive thanks for sharing
Best software testing training in chennai

Vicky Ram said...

Thanks for the excellent article. Very Informative blog.

Article submission sites
Guest posting sites

cdcdcdcd said...


it is really helpful. the information in this article is satisfied me. And the information it is very interesting. Thanks for this kind of article.


Deer Hunting Tips Camping Trips Guide DEER HUNTING TIPS travel touring tips

Anonymous said...

Great Post!
Thanks a lot for sharing!
I found this blog to be very useful!!
Software Testing training in Bangalore

Anonymous said...

Devops Training in Bangalore - Devops Training in Bangalore

dataexpert said...

This was really one of my favorite website. Please keep on posting. ExcelR Pune Digital Marketing Course

Anonymous said...

The blog is really amazing.

Big Data Hadoop Training In Chennai | Big Data Hadoop Training In anna nagar | Big Data Hadoop Training In omr | Big Data Hadoop Training In porur | Big Data Hadoop Training In tambaram | Big Data Hadoop Training In velachery

Anonymous said...

С сумкой для женщины всё сложно. Для женщины на основное место выходит то, как глядится сумка. Девушка принимает решение истратить свое время, чтобы привязаться к исключительной для себя сумочке в гардеробе, но несмотря ни на что произвести первое впечатление на подруг. В сумке женщины можно зафиксировать парфюм, медикаменты, визитки. Список может быть гораздо больше, всё зависит от наименования выбранного реквизита. В гардеробе девы одновременно несколько сумок разных принадлежностей и видов. Для посещения на работу или учёбу леди выбирает среднюю сумочку или сумку-портфель, для стрелки с одногруппниками днем. Занятно, что даме редко дарят сумку. Аксессуары девушка выбирает себе сама, а если есть потребность, то демонстрирует коллегам то, что она хочет в качестве желаемого подарка. Подарки и спонтанные приобретения здесь будут ненужны. Приобретение новой вещи – это важное событие, но черезмерно милое. Поэтому делайте это как можно чаще тут сумки майкл !

rocky said...

the article is very useful. I like that your blog.
Python Training in Chennai | Certification | Online Training Course | Python Training in Bangalore | Certification | Online Training Course | Python Training in Hyderabad | Certification | Online Training Course | Python Training in Coimbatore | Certification | Online Training Course | Python Training in Online | Python Certification Training Course

sherlie said...

Wow, Excellent post. This article is really very interesting and effective.you are posting a good information for people and keep maintain and give more update too.
Web Designing Training Course in Chennai | Certification | Online Training Course | Web Designing Training Course in Bangalore | Certification | Online Training Course | Web Designing Training Course in Hyderabad | Certification | Online Training Course | Web Designing Training Course in Coimbatore | Certification | Online Training Course | Web Designing Training Course in Online | Certification | Online Training Course

deiva said...

It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command .
web designing training in chennai

web designing training in omr

digital marketing training in chennai

digital marketing training in omr

rpa training in chennai

rpa training in omr

tally training in chennai

tally training in omr

Jayalakshmi said...

Very impressive and interesting blog, it was so good to read and useful to improve my knowledge as updated one,keep updating..This Concepts is very nice Thanks for sharing.
data science training in chennai

data science training in tambaram

android training in chennai

android training in tambaram

devops training in chennai

devops training in tambaram

artificial intelligence training in chennai

artificial intelligence training in tambaram

shiny said...

Thanks for the informative article. This is one of the best resources I have found in quite some time


data science training in chennai

data science training in annanagar

android training in chennai

android training in annanagar

devops training in chennai

devops training in annanagar

artificial intelligence training in chennai

artificial intelligence training in annanagar

jeni said...

Irrespective of rankings, this will help in huge traffic generation, on your website, over time and, in turn,will steadily increase the number of potential customers for your products and services.
sap training in chennai

sap training in velachery

azure training in chennai

azure training in velachery

cyber security course in chennai

cyber security course in velachery

ethical hacking course in chennai

ethical hacking course in velachery

Anonymous said...

Выбирая доступный стройматериал как, например, полированный керамогранит доведется отобрать максимальное число видов. Сфокусируйтесь не только на кафельной плитке заморского производства, но и на российские типы.

Anonymous said...

Разные коммунальные фирмы встают перед проблемой покупки различных строительного инвентаря. Стройинвентарь для коммунальной сферы по крайне актуальным ценам. Предприятие Снаб Топ поможет вам приобрести на сайте https://snabtop.ru/ по особо приемлемой стоимости на выгодных условиях.

Anonymous said...

Ответственный и проверенный импортер всегда сможет предоставить большой ассортимент кафельного покрытия для прихожей. Предприятие sotni.ru реализует geotiles geomix vendome 22.3 x 22.3 на протяжении десяти лет.

Anonymous said...

Компания Онлайн-займы предоставляет своим заказчикам 1000 рублей в долг и шанс отбора коммерческих формирований. Потребителям на этот раз нет нужды ходить в банк, с целью оформить нужную сумму. На свое усмотрение берите понравившийся коммерческий продукт на различные начинания.

Lavanya said...

this blog is really amazing and it is really very interesting and tremendous thanks for sharing those valuable information.salesforce training in chennai

software testing training in chennai

robotic process automation rpa training in chennai

blockchain training in chennai

devops training in chennai

Anonymous said...

Сервисная служба всегда поможет советом и мгновенно решит самую непростую задачу. Важно помнить, что казино х скачать на андроид бесплатно никогда не возьмет переводов за осуществление порядка регистрации гемблеров. Просмотреть подлинность игрового сервиса реально на официальной странице casino-x-oficialniy-sayt.com.

Anonymous said...

Продуманное меню и быстрый поиск – это гарантированный вариант найти интересную интерактивную игрушку. Три в ряд – максимально востребованный игровой автомат в ряду интерактивных игрушек КазиноХ. Всего лишь на данной платформе казино х играть на деньги вы можете нырнуть в сказочные приключения.

Anonymous said...

В азартных играх FrankCasino вы можете просто найти кнопку регистрации на заглавной странице портала. Присоединяйтесь к развлекательной платформе и получайте выгодные призы в персональной учетной записи. Осуществите рациональный выбор – зеркало frank ваш вариант на победу! Авторизация на площадке азартные игры «Франк-клуб» не отнимет много времени.

Anonymous said...

Пользователи соревнуются в тактике, формируют стопроцентные команды и побеждают в чемпионатах. Развлечения нынешнего поколения с отличными подарками. Киберспорт – это новый путь развития спортивных чемпионатов. Посетив казино mr bit зеркало вы окунетесь в удивительный мир игры на ПК.

Anonymous said...

Новейшее игральное заведение Joy Casino – это лучший способ подзаработать настоящие денежные средства. Проверить собственную фортуну возможно лишь посредством онлайн казино joycasino мобильная версия. Уникальный дизайн сайта приятен взору, а невероятное количество игр дает шанс поверить в личную удачу.

360digiTMG Training said...

I found Hubwit as a transparent s ite, a social hub which is a conglomerate of Buyers and Sellers who are ready to offer online digital consultancy at decent cost.
Best Data Science Courses in Hyderabad

rajmohan1140 said...

Hey there, You have done a fantastic job. I’ll definitely digg it and personally suggest to my friends. I am confident they will be benefited from this web site.

Java Training in Chennai

Java Course in Chennai

Anonymous said...

Хорошая прочность обеспечивает надежность материала на длительный срок. Горная порода, как стартовый компонент, не подлежит горению. Во время возникновения пожара realonda orly deco 44x44 не испаряет нежелательных веществ.

Anonymous said...

Приобрести дары моря http://www.markprom.ru/forums.php?m=posts&q=12243&n=last можно в поштучно или небольшими партиями. Поставка оформляется прямо на дату заказа. Для совершения заказа на рыбу в необходимом количестве достаточно обратиться к менеджеру или сделать удаленный заказ просто в интернет-магазине redgmshop.ru.

Anonymous said...

Всевозможные способы ворожения упоминаются как астральные науки. Определенный вид гадания уникален и предназначен для разнообразных результатов. Гадание на любовника на картах и истинность гаданий в основном зависит от умения человека. Каждый мечтает знать свою судьбу и воспринимает конкретные варианты предсказания будущего более эффективными.

Best Training Institute said...

I like your post. Everyone should do read this blog.
Perl training in bangalore

Anonymous said...

В новом интернет-магазине покупатель имеет возможность выбрать нужное устройство по доступной стоимости. Видеопроекторы являются отличным аналогом телевизору, однако имеют немного уникальных перспектив. https://www.projector24.ru/proektory/dlya-domashnego-kinoteatra/, расположенные на платформе Projector 24, – это наилучший вариант, что вы можете себе подумать!

Ashleel Londa said...

It was wonerful reading your conent. Thankyou very much. # BOOST Your GOOGLE RANKING.It’s Your Time To Be On #1st Page
Our Motive is not just to create links but to get them indexed as will
Increase Domain Authority (DA).We’re on a mission to increase DA PA of your domain
High Quality Backlink Building Service
Boost DA upto 15+ at cheapest
Boost DA upto 25+ at cheapest
Boost DA upto 35+ at cheapest
Boost DA upto 45+ at cheapest

IamLinkfeeder said...

David Forbes is president of Alliance Marketing Associates IncIamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder

Priya Rathod said...

HI, Such a nice blog and i appreciate your all efforts about your thoughts. it's really good work. well done.
AWS Training in Hyderabad
AWS Course in Hyderabad

Lokeswari said...

I think this is one of the best blog for me because this is really helpful for me. Thanks for sharing this valuable information

internship meaning | internship meaning in tamil | internship work from home | internship certificate format | internship for students | internship letter | Internship completion certificate | internship program | internship certificate online | internship graphic design

360DigiTMGMalaysia said...

20.After going through this post, I feel coming across this article was my best decision. This article helped me learn about Hadoop technology and why a training program from 360DigiTMG will help me advance my career and keep up with the competition. 360DigiTMG offers different courses for people and tells them to expand their practical, theoretical, and technical skills. Hadoop learning from 360DigiTMG will help you to effectively analyze, organize and extract valuable insights from data and even work with complex science technologies and machine learning algorithms in a seamless manner.
PMPTrainingMalaysia

jackdanieljihan said...

This blog, in my opinion, is among the best because it has been quite beneficial to me. I appreciate you sharing this useful information.

IELTS Coaching in Ahmedabad

Instaily Academy said...

This could be one of the most useful blogs I have ever come across on this technology. Find it very informative.

We also provide software courses.
IT Training Institute Kolkata - Instaily Academy

GCPMASTERS said...

Thanks for valuable information
gcp training

Import-Globals said...

For the most current and accurate information on Botswana trade statistics, I recommend checking Import Globals. For more information about global import export data visit our website.
Botswana Import Data

Let Me Think said...

I wholeheartedly concur with what you've said. Actually, after reading over your other writings, I do believe you to be quite accurate. Fantastic work on this webpage. SHARK TANK INDIA SEASON 3.