Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating infix function

Tags:

haskell

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
like image 421
Alan Coromano Avatar asked Dec 20 '22 00:12

Alan Coromano


2 Answers

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 :)

like image 157
Daniel Gratzer Avatar answered Jan 18 '23 02:01

Daniel Gratzer


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...

like image 36
David Miani Avatar answered Jan 18 '23 04:01

David Miani