我想分解此代码:
(* 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可以接受多少个参数。
感谢其他任何建议!
谢谢。
答案 0 :(得分:0)
一个潜在的解决方案可能是使用管道运算符而不是命名中间结果
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"