我建议创建一个包含问题标题、描述和解决方案的类型。然后,我将使用标准命名约定创建一个或多个模块,其中包含返回每个问题的解决方案的函数,例如
problemN
哪里
N
是
problemId
. 定义好后,我将使用反射来查找返回给定问题解决方案的函数,并调用它:
open System.Reflection
type Problem =
{
Title: string
Description: string
Solution: int // This could even be a function, int -> int or whatever
}
module Solutions =
let problem1 () =
{ Title = "#1"
Description = "The first problem"
Solution = 42
}
let printSolution problemId =
match Assembly.GetExecutingAssembly().GetTypes() |> Array.tryFind (fun t -> t.Name = "Solutions") with
| Some solutions ->
match solutions.GetMethod(sprintf "problem%d" problemId) with
| null ->
printfn "Solution to Problem %d not found" problemId
| func ->
let problem = func.Invoke(null, [||]) |> unbox<Problem>
printfn "Problem %d: %s" problemId problem.Title
printfn " %s" problem.Description
printfn " Solution = %d" problem.Solution
| None -> printfn "Solutions module not found"
你可以退回
Problem
实例而不是在实际库中打印它,但根据定义,您可以将其称为:
printSolution 1
它将打印以下内容:
Problem 1: #1
The first problem
Solution = 42
编辑
结合评论中对ifo20问题的回答和cadull提出的使用自定义属性的伟大建议,这里有一个更灵活的解决方案,允许在许多不同的模块/文件中定义解决方案,并且不依赖命名约定来找到它们。
open System
open System.Reflection
type Problem =
{
Title: string
Description: string
Solution: int // This could even be a function, int -> int or whatever
}
[<AllowNullLiteral>]
type SolutionModuleAttribute () =
inherit Attribute()
[<AllowNullLiteral>]
type SolutionAttribute (problemId: int) =
inherit Attribute()
member __.ProblemId = problemId
[<SolutionModule>]
module SomeSolutions =
[<Solution(1)>]
let firstProblem () =
{ Title = "#1"
Description = "The first problem"
Solution = 42
}
[<SolutionModule>]
module MoreSolutions =
[<Solution(2)>]
let secondProblem () =
{ Title = "#2"
Description = "The second problem"
Solution = 17
}
let findSolutions () =
Assembly.GetExecutingAssembly().GetTypes()
|> Array.filter (fun t -> t.GetCustomAttribute<SolutionModuleAttribute>() |> isNull |> not)
|> Array.collect (fun t -> t.GetMethods())
|> Array.choose (fun m ->
match m.GetCustomAttribute<SolutionAttribute>() with
| null -> None
| attribute -> Some (attribute.ProblemId, fun () -> m.Invoke(null, [||]) |> unbox<Problem>))
|> Map.ofArray
let printSolution =
let solutions = findSolutions()
fun problemId ->
match solutions |> Map.tryFind problemId with
| Some func ->
let problem = func()
printfn "Problem %d: %s" problemId problem.Title
printfn " %s" problem.Description
printfn " Solution = %d" problem.Solution
| None ->
printfn "Solution for Problem %d not found" problemId
除了使用属性来标识解决方案和包含这些解决方案的模块之外,最大的变化是将查找逻辑重构为它自己的函数。现在返回一个
Map<int, (unit -> Problem)>
因此,您只需遍历程序集并按其属性查找解决方案一次,然后就可以使用映射查找每个问题的解决方案。
的用法和输出
printSolution
功能保持不变:
printSolution 2
Problem 2: #2
The second problem
Solution = 17