Alan Coromano
Alan Coromano

Reputation: 26008

Creating infix function

I can define a function like this

method1 :: Int -> Int -> Int
method1 a b = a + b

main = print $ 1 `method1` 2

What if I don't want to use `` each time I call the function, but yet I want to use it in the infix form, how do I do that?

method1 :: Int -> Int -> Int
method1 a b = a + b

main = print $ 1 method1 2

Upvotes: 4

Views: 271

Answers (2)

David Miani
David Miani

Reputation: 14668

There is a vile and nasty "solution" to this - using a CPP macro. Eg:

{-# LANGUAGE CPP #-}

#define method1 `themethod`
module Main where

themethod x y = x + y

someValue = 3 method1 4

This compiles, and in ghci, someValue will equal 7. Please don't do this however...

Upvotes: 2

daniel gratzer
daniel gratzer

Reputation: 53871

Well the short answer is, you can't. Imagine the horrible ambiguity with a b c if b is potentially infix. But you can define an operator to do this for you. Any of these will work

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

Then

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

The permissible characeters for haskell's infix operators is limited, choose from

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

A common library, lens, has lots of operators that act as synonyms for longer names. It's quite common. Please do use judgement though, otherwise you'll end up with more perl than Haskell :)

Upvotes: 9

Related Questions