I have this code that I want to make point-free;
(\\k t -> chr $ a + flip mod 26 (ord k + ord t -2*a))
How do I do that?
Also are the
I am assuming that the point of your point-freeing is to make the code more concise and more readable. I therefore think that it is wise to also do some other refactorings towards simplification which then might make it easier to remove the variables.
(\k t -> chr $ a + flip mod 26 (ord k + ord t - 2*a))
First of all, the flip
is unnecessary:
(\k t -> chr $ a + (ord k + ord t - 2*a) `mod` 26)
Next, I would use name and conquer to factor out an independently usable subfunction:
encode_characters k t = chr $ encode (ord k) (ord t)
encode x y = (x + y - 2*a) `mod` 26 + a
I also gave a name to the first expression to make it clearer and reusable. encode_characters
is now easy to make point-free using the technique from @Nefrubyr:
encode_characters = chr . encode `on` ord
As for the second expression, I cannot produce a form that's more readable than any shown in the other answers and they're all less readable than the point-wise form. I would therefore suggest to stop refactoring at this point and admire the cleanliness and reusability of the resulting code.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PS: as an exercise, depending on the context of the problem, some slight modification of the function interfaces (what data in what form is passed into the functions) might yield more simplifications by generalizing the problem.
A. Implement and simplify function encode_n_characters :: [Char] -> Char
where encode_characters k t = encode_n_characters [k, t]
. Is the result simpler than the specialized two-argument function?
B. Implement a function encode'
defined via encode' (x + y) = encode x y
and reimplement encode_characters
using this function. Does either of the functions become simpler? Is the implementation simpler overall? Is encode'
more or less reusable than encode
?