Best way to choose a state for an Unfold? #2907
Unanswered
clintonmead
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Bit of a question about how to best use streamly to get well optimised code. Sorry if there's documentation that already answers this, I couldn't find any sorry.
So I've got what I think is a fairly standard unfold, that is something like this form:
So then I can do this:
So far so good. But it occurred to me that parts (1) and (3) above are basically inverses. Why am I producing a state enum just to pattern match on it and turn it back into a function call? My function
f1
knows what function I need to call next (namelyf2
in this case), why not just put that directly into the state instead of converting it into an enum. So then it occurred to me that I could do this:And I can then just write this function, which is just a slightly transformed version of
f
:And I can just call
g1 data
org2 data
or whatever depending on what my initial state is to kick off the process.Now I avoid the pattern match on states at the start of each function. I just have inside my state thunk that resolves to what happens next.
In some way this seems more direct. Instead of basically making a mapping between an enum and a function call through a case statement, and storing the enum in the state as a proxy for the next function to be called (which requires the extra time of a pattern match to result), I'm just storing the next function to be used directly. But there are some issues:
streamly
is designed to apply?Just thinking out loud, I guess the case match is a pattern match followed by a direct jump (i.e. one that's location is known at compile time). Whereas storing the thunk avoids the pattern match but is an indirect jump. That's two things in the first case but only one in the second but perhaps the latter it a "bigger thing", as perhaps building a thunk is slower than building and enum and pattern matching on it.
But I guess the bigger thing is what is GHC happier to optimise? Is it best to map my "continuation function" to an enum and store that in the state, or just store a thunk to the "continuation function" directly?
Beta Was this translation helpful? Give feedback.
All reactions