2

Say I have a data type, with hundreds of data constructors:

data Goo 
  = Goo001
  | Goo002
  | Goo003
  ...
  | Goo999

and I make a function that pattern matches on every one of those constructors:

  func :: Goo -> Int
  func Goo001 = 78
  func Goo002 = 93
  func Goo003 = 789
  ...
  func Goo999 = 1

Does GHC optimize the different function equations in any way, so that to match Goo999, it doesn't have to try to match on all the previous 998 equations?

Or would it be better to make a Data.Map Goo Int and make func do a lookup on that map?

bwroga
  • 5,379
  • 2
  • 23
  • 25
  • It uses binary search iirc. But a jump table might be better: https://gitlab.haskell.org/ghc/ghc/issues/9159 – Willem Van Onsem Feb 29 '20 at 18:10
  • @WillemVanOnsem No, that's for matches on numerical types like `Int#`. If you test this case it becomes a Cmm `switch`, which I presume *is* a jump table. According to a comment in your linked thread, this is because the range of possible numerical values is known to be contiguous and there's no chance of it being out of bounds, so a jump table works easily. – HTNW Feb 29 '20 at 18:24
  • @HTNW: ah, ok. Well bwroga: then it uses a jump table :). – Willem Van Onsem Feb 29 '20 at 18:26
  • I have closed this against a Q&A that covers the jump table usage discussed in these comments. Ping me if you think there's something in your question left unaddressed. – duplode Feb 29 '20 at 18:45
  • @duplode No problem, that question covers everything I wanted to know – bwroga Feb 29 '20 at 19:25

0 Answers0