Skip to content

Friendly OK and Err Helpers #331

Closed
@devigned

Description

@devigned

The generic signatures for cm.OK and cm.Err are somewhat challenging to construct. Consider the following example:

chat.Exports.Chat = func(request chat.ChatRequest) cm.Result[chat.ChatResponseShape, chat.ChatResponse, chat.Error] {
	res, err := chatCompletion(request)
	if chatErr, ok := err.(chatError); ok {
		return cm.Err[cm.Result[chat.ChatResponseShape, chat.ChatResponse, chat.Error]](chat.Error{ ... })
	}
	return cm.OK[cm.Result[chat.ChatResponseShape, chat.ChatResponse, chat.Error]](res)
}

My first attempt to writing that code looked looked like the following, but there is not enough type information to satisfy (in call to cm.Err, cannot infer R)

chat.Exports.Chat = func(request chat.ChatRequest) cm.Result[chat.ChatResponseShape, chat.ChatResponse, chat.Error] {
	res, err := chatCompletion(request)
	if chatErr, ok := err.(chatError); ok {
		return cm.Err(chat.Error{ ... })
	}
	return cm.OK(res)
}

Perhaps, there's an opportunity to generate helper functions for each exported function such that the code could look like the following.

chat.Exports.Chat = func(request chat.ChatRequest) cm.Result[chat.ChatResponseShape, chat.ChatResponse, chat.Error] {
	res, err := chatCompletion(request)
	if chatErr, ok := err.(chatError); ok {
		return chat.ChatErr(chat.Error{ ... })
	}
	return chat.ChatOK(res)
}

Another alternative could be to create a type alias for the result generic. It could look like the following.

chat.Exports.Chat = func(request chat.ChatRequest) chat.ChatResult {
	res, err := chatCompletion(request)
	if chatErr, ok := err.(chatError); ok {
		return cm.Err(chat.ChatResult(chat.Error{ ... }))
	}
	return cm.OK(chat.ChatResult(res))
}

Please forgive the stuttering with the package name and function name.

The main point is that with the code generation, it's relatively simple to generate these helpers which will hide a bit of the generic complexity. I believe that will make it a bit easier for folks.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions