0

I really love using total functions. That said, sometimes I'm not sure what the best approach is for guaranteeing that. Lets say that I'm writing a function similar to chunksOf from the split package, where I want to split up a list into sublists of a given size. Now I'd really rather say that the input for sublist size needs to be a positive int (so excluding 0). As I see it I have several options:

1) all-out: make a newtype for PositiveInt, hide the constructor, and only expose safe functions for creating a PositiveInt (perhaps returning a Maybe or some union of Positive | Negative | Zero or what have you). This seems like it could be a huge hassle.

2) what the split package does: just return an infinite list of size-0 sublists if the size <= 0. This seems like you risk bugs not getting caught, and worse: those bugs just infinitely hanging your program with no indication of what went wrong.

3) what most other languages do: error when the input is <= 0. I really prefer total functions though...

4) return an Either or Maybe to cover the case that the input might have been <= 0. Similar to #1, it seems like using this could just be a hassle.

This seems similar to this post, but this has more to do with error conditions than just being as precise about types as possible. I'm looking for thoughts on how to decide what the best approach for a case like this is. I'm probably most inclined towards doing #1, and just dealing with the added overhead, but I'm concerned that I'll be kicking myself down the road. Is this a decision that needs to be made on a case-by-case basis, or is there a general strategy that consistently works best?

Nathan Wilson
  • 629
  • 6
  • 11
  • 5
    It's something you need to decide on a case-by-case basis. `chunkOf` inherits `take`'s behavior, which is to treat any negative argument the same as 0, and for `take`, that makes sense. Other functions might not have a suitable default, in which case using `Maybe` makes more sense to force you to deal with a bad input. If you are using Liquid Haskell, defining a dependent type like `PositiveInt` becomes a lot easier. – chepner Apr 03 '19 at 19:12
  • 1
    woah, I've never heard of Liquid Haskell. It looks really powerful. I'll have to investigate that further. – Nathan Wilson Apr 03 '19 at 19:22
  • 1
    See also [Positive integer type](https://stackoverflow.com/q/11910143/791604). – Daniel Wagner Apr 03 '19 at 19:40
  • Related: https://stackoverflow.com/questions/39810259/limit-a-number-to-a-range-haskell and this post https://www.parsonsmatt.org/2018/10/02/small_types.html – danidiaz Apr 03 '19 at 19:58
  • Yeah LH is great for stuff like this – luqui Apr 04 '19 at 03:45

0 Answers0