Home > Software engineering >  Haskell constants in functions
Haskell constants in functions

Time:02-23

I was wondering if someone could explain to me what (-2)(-2) in the brackets in the first line of the code stand for. I am new to Haskell and I’m trying to understand.

to_up_left board (x, y, t, c) (-2)(-2) = to_up_left board (x, y, t, c) x y
to_up_left board (x, y, t, c) 0 _ = []
to_up_left board (x, y, t, c) _ 9 = []
to_up_left board ((-1), y, t, c) _ _ = []
to_up_left board (x, y, t, c) _x _y =  if (empty_field board (_x-1) (_y 1))  && (t == 'a' || t == 'A' )
                            then    concat [decode_x x    decode_y y    "-"    decode_x (_x-1)    decode_y (_y 1)]:     to_up_left board (x, y, t, c) (_x-1)  (_y 1) 
                            else if   (friend_on_field board  (_x-1) (_y 1)) &&   (t == 'a' || t == 'A' )
                                then   concat [decode_x x    decode_y y    "-"    decode_x (_x-1)   decode_y (_y 1)]: []
                                else     []

CodePudding user response:

if someone could explain to me what (-2) (-2) in the brackets in the first line of the code stand for.

This is to pattern match with negative numbers, otherwise it will be interpreted as

(to_up_left board (x, y, t, c)) - (2 (-2))

and it thus seems that you are defining a (-) function. Negative numbers should thus be specified between parenthesis. The parenthesis have no special meaning: you can nest it an arbitrary number of times ((-2)) for example.

CodePudding user response:

The function to_up_left has 4 arguments. In the top line:

  • board is the first argument
  • (x, y, t, c) is the second argument
  • (-2) is the third argument
  • (-2) is the fourth argument.

The (-2) arguments need their parentheses because otherwise - would act as a binary operator.

Haskell function definitions do pattern matching:

  • board names its argument, just as in C-like languages
  • (x,y,t,c) expects a 4-tuple, and binds the 4 elements to separate names
  • (-2) checks to see if the argument is equal to -2
    • if the third and fourth arguments are not both -2, try the next pattern
  • Related