1

I need to analyze the following Haskell function, which is part of a bigger program (extracted from here):

findMoves :: Position -> [Position]
findMoves (left,right) = elems $ Data.Set.filter validPos moves where
    moves | Farmer `member` left = Data.Set.map (move delItem addItem) left
          | otherwise = Data.Set.map (move addItem delItem) right
    move f1 f2 item = (f1 item left, f2 item right)
    delItem item = delete Farmer . delete item 
    addItem item = insert Farmer . insert item 

I understand everything until the end of the where statement, but I haven't seen anything like the move f1 f2 item declaration before, I'm starting right now with Haskell. What is that? Something like an in-line function declaration? I just need to know which kind of statement is that, I'm not asking you to explain what the developer was trying to do (that's my task).

Thanks

pitazzo
  • 1,125
  • 1
  • 13
  • 28
  • The `move` function is declared **in** the `where` clause. – Willem Van Onsem Jun 04 '18 at 15:28
  • @WillemVanOnsem which kind of functio is it? Shouldn't it be declared apart, with its own signature? – pitazzo Jun 04 '18 at 15:31
  • no, not per se. Here it uses variables from the *outer* function, so it can not immediately be declared outside. Frequently a `where` clause contains functions that are tight to the outer function, but are not very generic, etc. to define separately. – Willem Van Onsem Jun 04 '18 at 15:33
  • Its definition is exactly `move f1 f2 item = (f1 item left, f2 item right)`, as shown above. Some authors tend to add type signatures to local functions in where blocks (I do, since I believe it helps greatly), but many do not, relying on type inference. – chi Jun 04 '18 at 15:34

1 Answers1

4

Maybe take a look at some easier example and see if we can figure out what's going on

foo :: Int -> (Int, Int)
foo x =  apply add sub x
    where
    apply f1 f2 someThing = (f1 x someThing, f2 x someThing)
    add k = (+) (1) --<---------------^
    sub s = (-) (10) -- <-----------------------------^

With the input 5, this would give output (6,5). It can often be useful to say something like "i want to apply x to some function", where this function itself takes other functions as input. So we can make it more general by saying: here is a function, that together with 2 other functions, gives me my desired output.

In the short example above we say, "here is a function, that together with two other functions, applies those functions with some values to make a pair". And we dont really care what those functions are, in this case we used the functions add and sub, but that doesnt have to be the case.

JohEker
  • 627
  • 5
  • 13