0

Could I define an anonymous function without parameter in Haskell?

I have a block of code repeated in several branches. Those code refer to several values outside.

Purpose 0: Define a function do the job in the codeBlock.

Purpose 1: Don't repeat codeBlock twice.

Purpose 2: Don't pass d1..d4 to the function. Avoid passing file and time even better.

f event d1 d2 d3 d4 =
  case event of
    (Modified file time) -> do
       codeBlock file time d1 d2 d3 d4 
    (Added file time) -> do
       codeBlock file time d1 d2 d3 d44
    _ -> return ()
8
  • 1
    If you want to use a block of code (with or without parameters, in Haskell or in another language) several times without repeating it, you generally need to give it a name. Commented Oct 19, 2015 at 5:46
  • 4
    You can just lift the repeated code into a let, i.e. you can turn x = case y of P1 -> f largeCodeBlock foo; P2 -> g bar largeCodeBlock into x = let lcb = largeCodeBlock in case y of P1 -> f lcb foo; P2 -> g bar lcb. Is this what you're after? (I'm happy to post this as an answer if yes.) Commented Oct 19, 2015 at 5:48
  • 10
    to give you a short answer: functions without parameters are called values ;) Commented Oct 19, 2015 at 5:54
  • 1
    Can you show us this code? It may depend on context. Commented Oct 19, 2015 at 6:38
  • 3
    @highfly22 what's wrong with where? Did you place it at the proper scope level? If not it may be in scope only for one of the case branches (its indentation must be the same as the word "case") Commented Oct 19, 2015 at 7:41

1 Answer 1

4

There is no such thing as a function without parameters (anonymous or otherwise). That's just a value (and in Haskell, actions like main :: IO () are also just values).

For sure, a value can be defined anywhere (like a function); however if you want to reuse it in more than one place you should not make it anonymous but give it a (locally scoped) name:

f event d1 d2 d3 d4 =
  case event of
    (Modified file time) -> do
       defaultAction time
    (Added file time) -> do
       defaultAction time
    _ -> return ()
 where defaultAction time = do
           codeBlock file time d1 d2 d3 d4

BTW, do blocks with only a single statement are equivalent to just that statement alone, i.e. you could also write

f event d1 d2 d3 d4 =
  case event of
    (Modified file time) -> defaultAction time
    (Added file time) -> defaultAction time
    _ -> return ()
 where defaultAction time = codeBlock file time d1 d2 d3 d4
Sign up to request clarification or add additional context in comments.

2 Comments

The second example gives "Not in scope: : ‘time’".
I see. So the anonymous function you've wanted doesn't even have zero parameters...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.