Fl4m3Ph03n1x
Background
I have come up with a solution to the Caeser Cipher challenge in Exercism.io. This solution works and passes all tests, but I am still not happy.
Code
defmodule RotationalCipher do
@doc """
Given a plaintext and amount to shift by, return a rotated string.
Example:
iex> RotationalCipher.rotate("Attack at dawn", 13)
"Nggnpx ng qnja"
"""
@spec rotate(text :: String.t(), shift :: integer) :: String.t()
def rotate(text, shift) do
text
|> String.to_charlist()
|> Enum.map( fn char ->
cond do
is_lower_case?( char ) -> rotate_lower_case( char, shift )
is_upper_case?( char ) -> rotate_upper_case( char, shift )
true -> char
end
end )
|> to_string()
end
defp is_lower_case?( char ), do: char >= 97 && char <= 122
defp rotate_lower_case( char, shift ), do: 97 + rem( char - 71 + shift, 26 )
defp is_upper_case?( char ), do: char >= 65 && char <= 90
defp rotate_upper_case( char, shift ), do: 65 + rem( char - 39 + shift, 26 )
end
So, given a string and a shift, I have to shift all the letters. Punctuation, numbers and spaces remain the same.
I achieve this by converting the string to a charlist, mapping over it, and then converting the result into a string again. But in my eyes, there is room for better.
Possible improvements
- I had to define
is_upper_case?andis_lower_case?for characters. Isn’t there a built in function that already does this? - In my
Enum.mapI have a function that I would like to extract into adefp, for the sake of clarity. But I still don’t know how to do it and I only found answer that tell me how to use anonymous functions with the terse syntax. How would I call an already defined function that takes more than 1 parameter inside anEnum.map? - I am using a conditional, even though I have the feeling I shouldn’t be using one yet. The exercise is supposed to be about string only but I am already using control flow. I have the feeling I am over complicating. Perhaps there is a simpler solution?
Let me know what you guys think!
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
Hi everyone,
I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding.
I sta...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted”
Version...
New
Other Trending Topics
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself.
My main conc...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixirconf-us
- #ai
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #elixirconf-eu
- #metaprogramming
- #hex










Showing Posts 5 to 1- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
datadrover
Completely agree with the comment about Dave Thomas’s video course. I also think that Lance Halvorsen’s book, should be on the reading list of anyone wanting to deploy a basic understanding of Elixir to the construction of larger applications.
Getting back to to the topic, this version was inspired by the treatment of comprehensions on bitstrings in the Dave Thomas book (p108 in my 2016 1.3 edition):
It’s not as elegant as kip’s solution, but it is easy to follow.
malloryerik
Kip’s is amazing with the binary pattern matching, which goes into the string itself like it has superpowers. Here’s my more pedestrian beginner’s attempt, with run-of-the-mill guards and very basic pattern matching – no advanced features. Everything here is in the first parts of the Getting Started guide on elixir-lang.org. It does seem easy to read.
Everything you’d think of as conditional logic has been moved to the function headers, using guards in this case. Of course you could write a more traditionally conditional version:
I find the first version more direct.
By the way, AstonJ in this forum has been recommending Dave Thomas’ Elixir for Programmers video course. I tried it and have found it an excellent addition to books because you (or at least I) get a sense of workflow and state of mind along with a great introduction to OTP.
Fl4m3Ph03n1x
Thanks for the feedback everyone!
@NobbZ yah, thanks for pointing out about the labels. It was making me feel really worthless not being able to do an exercise that was supposed to be super simple and have no conditionals. Turns all the solutions use some advanced feature, so it’s good to know that I should have a bigger level in Elixir before attempting Exercism. Now I understand why @peerreynders suggested me to read the book first and then do the exercises !
@kip Your solution is probably awesome, but I am too young to appreciate it. This happens because I am still learning the basics of Elixir and I have no idea what guards are, let along all the <<>> thing going on. Along with that binary strings are still a somewhat vague concept. I mean, for one of the 1st exercises in Exercism I would expect something simpler.
I will likely return to this later and try to appreciate it for it’s full glory
kip
@Fl4m3Ph03n1x, I think this is a good case for binary pattern matching.
NobbZ
No, there is not.
At least when I understand you correctly.
Don’t take the abscense of the control flow label too strict. those labels are relatively new and they haven’t been applied thoroughly yet. This is a problem common to most tracks.
Have you considered using a
Rangeand charliterals? eg.char in ?a..?z.But in general I think it looks quite good already.