首页 > 解决方案 > 如何通过另一个函数获取结果过程的倍数函数?

问题描述

我想分解这段代码:

(* 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 可以接受多少参数。

任何其他建议表示赞赏!

谢谢你。

标签: refactoringocaml

解决方案


一个潜在的解决方案可能是使用管道运算符而不是命名中间结果

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"

推荐阅读