Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - pattern matching syntactic sugar and where

Tags:

Often I have a function of such pattern:

f :: a -> b
f x = case x of
  ... -> g ...
  ... -> g ...
  ...
  ... -> g ...
  where g = ...

There is an syntactic sugar for almost this case:

f :: a -> b
f ... = g ...
f ... = g ...
...
f ... = g ...

Unfortunately I can't attach my where to it: I'll obviously get bunch of not in scopes. I can make g a separate function, but it's not nice: my module's namespace will be polluted with utility functions. Is there any workaround?

like image 802
Matvey Aksenov Avatar asked Jan 19 '12 19:01

Matvey Aksenov


2 Answers

I think that your first example isn't bad at all. The only syntactic weight is case x of, plus -> instead of =; the latter is offset by the fact that you can omit the function name for each clause. Indeed, even dflemstr's proposed go helper function is syntactically heavier.

Admittedly, it's slightly inconsistent compared to the normal function clause syntax, but this is probably a good thing: it more precisely visually delimits the scope in which x is available.

like image 144
ehird Avatar answered Sep 16 '22 16:09

ehird


No, there is no workaround. When you have multiple clauses for a function like that, they cannot share a where-clause. Your only option is to use a case statement, or do something like this:

f x =
  go x
  where
    go ... = g ...
    go ... = g ...
    g = ...

...if you really want to use a function form for some reason.

like image 31
dflemstr Avatar answered Sep 20 '22 16:09

dflemstr