Defining a function with protection

The classic way to define Haskell functions

f1 :: String -> Int f1 ('-' : cs) -> f1 cs + 1 f1 _ = 0 

I am a bit dissatisfied with writing the function name on each line. Now I usually write as follows, using the extension of template templates and considering it to be more readable and modifiable:

 f2 :: String -> Int f2 s | '-' : cs <- s = f2 cs + 1 | otherwise = 0 

Do you think the second example is more readable, modifiable, and elegant? What about the generated code? (I did not have time to see how it went out of print, sorry!). What are the cons? The only thing I see is the use of extensions.

+4
source share
2 answers

I prefer to write the name of the function when I map the templates to something that is shown in your case. I find this more readable.

I prefer to use guards when I have some conditions for function arguments, which helps to avoid the if else , which I would have to use if I had to follow the first pattern.

So, to answer your questions

 Do you think that second example is more readable, modifiable and elegant? 

No, I prefer the first one, which is simple and readable. But more or less it depends on your personal taste.

 What about generated code? 

I don’t think there will be any difference in the generated code. Both are just templates.

 What are cons? 

Well pattern sets are useful for patternmatch instead of using let or something cleaner.

 addLookup env var1 var2 | Just val1 <- lookup env var1 , Just val2 <- lookup env var2 = val1 + val2 

Well, of course, you need to use the extension, and also it is not Haskell98 (which you might not consider part of con)

On the other hand, for trivial pattern matching in function arguments, I simply use the first, simple and readable method.

+6
source

Well, you can always write like this:

 f3 :: String -> Int f3 s = case s of ('-' : cs) -> f3 cs + 1 _ -> 0 

This means the same as version f1 . If a function has a long or other hard-to-read name, and you want to combine with a lot of templates, this is likely to be an improvement. For your example, I would use the usual syntax here.

There is nothing wrong with your version of f2 as such, but it seems slightly unreasonable to use the GHC syntax extension, which is not common enough to suggest that everyone will be familiar with it. For personal code, this does not really matter, but I would stick with the case expression for everything you expect others to read.

+8
source

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


All Articles