Creating an infix Function

I can define a function like this

method1 :: Int -> Int -> Int method1 ab = a + b main = print $ 1 `method1` 2 

What if I do not want to use `` every time I call a function, but still I want to use it in the form of an infix, how to do this?

 method1 :: Int -> Int -> Int method1 ab = a + b main = print $ 1 method1 2 
+4
source share
2 answers

Well, the short answer is you cannot. Imagine a terrible ambiguity with abc if b potentially infix. But you can define an operator for this. Any of them will work

 a |+| b = method1 (|+|) ab = method1 ab (|+|) = method1 

Then

 a |+| b === a `method1` b === method1 ab 

Valid characters for infix haskell statements are limited, select

 :| !@ #$%^&*-+./<>?\~ 

In the shared library, the lens, there are many operators that act as synonyms for longer names. This is pretty common. Please use judgment, although otherwise you will get more perl than Haskell :)

+9
source

To do this, there is a vile and nasty "solution" - using the macro CPP. For instance:

 {-# LANGUAGE CPP #-} #define method1 `themethod` module Main where themethod xy = x + y someValue = 3 method1 4 

This compiles, and in ghci someValue will be 7. Please do not do this, however ...

+2
source

Source: https://habr.com/ru/post/1500428/


All Articles