Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap function in haskell?

Tags:

haskell

addMod26 a b = (a + b) `mod` 26
char2Int c = ord c - (ord 'a')
int2Char i = chr (i + (ord 'a'))
addChar a b = int2Char ((addMod26 `on` char2Int) a b)

This code try to implement add operation on char. It work well. But function addChar is too redundancy. How to simplify it?

try to write like this

addChar = int2Char . (addMod26 `on` char2Int)

It's wrong. (.) :: (b -> c) -> (a -> b) -> a -> c cannot accept (b -> b -> c) as it's first argument.

any good idea, or suggestion?

like image 403
liuyang1 Avatar asked Jan 21 '26 10:01

liuyang1


1 Answers

If you want to write addChar in point-free form, it would be:

addChar = (int2Char .) . (addMod26 `on` char2Int)

Or:

addChar = int2Char .: (addMod26 `on` char2Int)

Where (.:) = (.) . (.), which composes a unary function with a binary function:

(.:) :: (c -> d) -> (a -> b -> c) -> a -> b -> d

You can discover these refactorings using the pointfree tool, although its results tend to be ugly.

like image 106
Jon Purdy Avatar answered Jan 23 '26 08:01

Jon Purdy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!