refactoring - 如何通过另一个函数获取结果过程的倍数函数?
问题描述
我想分解这段代码:
(* This function is applied to the result of functions below *)
let manage_result r s =
match r with
| Error ( `Msg e ) -> Tsdl.Sdl.log s e;exit 1
| Ok a -> a
(* Examples of function I want to factorize, let's call them f_functions, f for factorize *)
let init () =
let flag = Tsdl.Sdl.Init.everything in
let result = Tsdl.Sdl.init flag in
manage_result result "Init error : %s"
let create_window title w h =
let flag = Tsdl.Sdl.Window.windowed in
let result = Tsdl.Sdl.create_window title ~w:w ~h:h flag in
manage_result result "Create window error : %s"
let get_window_surface window =
let result = Tsdl.Sdl.get_window_surface window in
manage_result result "Get window surface error : %s"
如您所见,所有这些 f_functions 的最后两行非常相似。我想创建一个将函数作为参数的函数(例如,如果我想分解init,作为参数传递的函数将是Tsdl.Sdl.init
)并返回一个函数,该函数返回作为参数传递的函数的返回值并处理通过manage_result
.
困难在于我不知道 f_functions 可以接受多少参数。
任何其他建议表示赞赏!
谢谢你。
解决方案
一个潜在的解决方案可能是使用管道运算符而不是命名中间结果
let on_error s r = manage_result r s
let create_window title w h =
let flag = Tsdl.Sdl.Window.windowed in
Tsdl.Sdl.create_window title ~w:w ~h:h flag
|> on_error "Create window error : %s"
更进一步,我们可以为错误处理定义一个自定义运算符
let ( <!> ) = manage_result
这可能会使您的定义足够轻量级
let create_window title w h =
let flag = Tsdl.Sdl.Window.windowed in
Tsdl.Sdl.create_window title ~w:w ~h:h flag
<!> "Create window error : %s"
推荐阅读
- reactjs - 剪辑路径动态转换以填充容器
- python - axios响应是一个字符串,里面有回车,应该是一个数组
- aws-device-farm - 为什么 Appium python find_element_by_id 在 AWS 设备场中失败但在本地工作?
- github - 创建 github 站点/自定义页面/多个项目
- python - one_shot_iterator,占位符,无法捕获占位符
- c - 如何在不输入命令提示符的情况下将光标移动到下一行?
- c++ - 将一个类的对象声明为另一个类的成员 (C++)
- spring - xwEx 对 log4j2 的含义?
- c# - C#:通过单例类访问类的实例时如何修复 System.TypeInitializationException?
- python - 试图在 Python 中获取 .wav 文件的频率