Operator as an argument in Haskell

I'm new to Haskell, maybe this is a dumb question. I want to give my function as argument any operator. For instance:

myFunc :: a -> Int -> Int -> Boolean
myFunc operator a b = a operator b

*Project> myFunc (>) 5 2
True
*Project> myFunc (<=) 5 2
False

Help me in advice on how to do this, please!

+4
source share
2 answers

You can do this with haskell function arguments. In the function above, you want to myFuncexecute a function that takes two Intand returns Bool(and not Boolean, you had to enter the wrong one). The announcement of this function will be (Int -> Int -> Bool). Therefore you can write:

myFunc :: (Int -> Int -> Bool) -> Int -> Int -> Bool
myFunc op a b = a `op` b

, Int, Bool ( Int s). , !

, , :

myFunc (#) a b = a # b

:

myFunc (%) a b = a % b

infix, * /, , , - ( `/` , -, !).

+8

"" . , ( ), myFunc just , , , . , x = 3: 3 "" x, .

?

, Haskell, > <= , > <=. ( , ) , .

Haskell . - ( , ) ( ). {1} {2} {3}, {2} ( {1} {3} , ), " {2} {1} {3}". , " {1} {2} {3}". 1

, , . , myFunc :

myFunc operator a b = operator a b

, myFunc myFunc (+) 1 2 myFunc plus 1 2; myFunc "" operator, - . , , , .

myFunc, :

myFunc ($&^*) a b = a $&^* b

, , myFunc - , myFunc plus 1 2.

, , , ; - backticks, infix :

myFunc operator a b = a `operator` b

, ( ):

myFunc ($^&*) a b = ($&^*) a b

, , , , , - , : , . , ; , , , . ( ), "" .


1 , , 3- , , , .

+6

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


All Articles