algorithmsbooks / optimization

Errata for Algorithms for Optimization book
68 stars 16 forks source link

Julia beginner #49

Closed AlexandrParkhomenko closed 3 years ago

AlexandrParkhomenko commented 3 years ago

Thanks for the book. I have a simple entry-level question. How to assemble a FactorTable correctly?

julia-1.5.4:

struct Variable
    name::Symbol
    m::Int # number of possible values
end

const Assignment = Dict{Symbol,Int}
const FactorTable = Dict{Assignment,Float64}
struct Factor
    vars::Vector{Variable}
    table::FactorTable
end
B = Variable(:b, 2);
FactorTable((b = 1,) => 0.99, (b = 2,) => 0.01);

Code on page 26 "chapter 2 representation" throw exception.

ERROR: LoadError: MethodError: Cannot `convert` an object of type NamedTuple{(:b,), Tuple{Int64}} to an object of type Dict{Symbol, Int64}
Closest candidates are:
  convert(::Type{T}, ::T) where T<:AbstractDict at abstractdict.jl:520
  convert(::Type{T}, ::AbstractDict) where T<:AbstractDict at abstractdict.jl:522
  convert(::Type{T}, ::T) where T at essentials.jl:205
  ...
mykelk commented 3 years ago

I think you may have intended this issue for this repo: https://github.com/algorithmsbooks/decisionmaking

You'll need the code in Appendix G.5:

Base.Dict{Symbol,V}(a::NamedTuple) where V =
   Dict{Symbol,V}(n=>v for (n,v) in zip(keys(a), values(a)))
Base.convert(::Type{Dict{Symbol,V}}, a::NamedTuple) where V =
   Dict{Symbol,V}(a)
Base.isequal(a::Dict{Symbol,<:Any}, nt::NamedTuple) =
   length(a) == length(nt) &&
   all(a[n] == v for (n,v) in zip(keys(nt), values(nt)))
AlexandrParkhomenko commented 3 years ago

Thanks a lot. I am very proud that I live in the same era with great people.