function - 如何从 Julia 结构的构造函数中调用函数?

标签 function methods constructor julia blockchain

我是一名具有 C++ 和 Python 背景的程序员,最近偶然发现了 Julia,我真的很喜欢它所提供的功能。为了同时更加熟悉区 block 链实现和 Julia,我有点雄心勃勃,尝试通过转换 Hackernoon 发布的 Python 实现,在 Julia 中创建区 block 链的基本实现。 (作者解释了每种方法应该比我做得更好)。

但是,我在创建实际的 Blockchain 结构时遇到了问题。为了创建创世 block ,Hackernoon 建议我在构造函数中调用成员函数 new_block。到目前为止,我还没能弄清楚如何在 Julia 中最好地复制这一点。这是我到目前为止所拥有的:

import JSON
import SHA

mutable struct Blockchain
    chain::Array{Dict{String, Any}}
    current_transactions::Array{String}
    block::Dict{String, Any}
    new_block::Function

    function Blockchain(chain::Array{Dict{String, Any}}, current::Array{String})    
        new(chain, current, new_block(previous_hash=1, proof=100)) 
        # ^issue calling function within the constructor here
    end
end

当我尝试运行代码时,出现以下错误:

常量区 block 链的重新定义无效

这是new_block函数:

function new_block(proof::String, previous_hash::String=nothing)
    block = Dict(
    "index" => length(chain) + 1,
    "timestamp" => time(),
    "transactions" => current_transactions,
    "proof" => proof,
    "previous_hash" => previous_hash | hash(chain[end]),
    )
    current_transactions = []
    append!(chain, block)
    return block
end

以下是我目前拥有的其余功能:

function new_transaction(this::Blockchain, sender::String, recipient::String, amount::Int)
    
     transaction = Dict(
        "sender"=> sender,
        "recipient"=> recipient,
        "amount"=> amount,
     )

    append!(this.current_transactions, transaction)

    return length(this.chain) + 1
end

function hash(block::Blockchain)
    block_string = JSON.dumps(block, sort_keys=true).encode()
    return sha256(block_string).hexdigest()
end

我可能对 Julia 中类型/结构的工作方式有一些误解;我的大部分信息都是从第三方网站以及官方文档中获得的。以下是我一直依赖的一些来源:

如果能以更聪明/更有效的方式来实现我的目标,我将不胜感激。

编辑:

以下是我根据给定的建议所做的一些更改:

struct Blockchain
    chain::Array{Dict{String, Any}}
    current_transactions::Array{String}

    function Blockchain(chain::Array{Dict{String, Any}}, current::Array{String})    
        new(chain, current)
    end
end

function new_block!(this::Blockchain, proof::Int, previous_hash::Int=nothing)
    block = Dict(
    "index" => length(this.chain) + 1,
    "timestamp" => time(),
    "transactions" => this.current_transactions,
    "proof" => proof,
    )
    if previous_hash == nothing
        block["previous_hash"] = hash(this.chain[end])
    else
        block["previous_hash"] = previous_hash
    end

    this.current_transactions = []
    append!(this.chain, block)
    return this
end

我意识到block属性没有用,因为它的存在只是为了添加到中,所以我删除了它。

此外,这里是一个没有内部构造函数的备用 Blockchain 定义:

struct Blockchain
    chain::Array{Dict{String, Any}}
    current_transactions::Array{String}
    
    Blockchain(x::Array{Dict{String, Any}}, y::Array{String}) = new(x, y)
end

最佳答案

免责声明。这可能不一定是您问题的答案。但我想将其作为答案发布,因为评论不允许让我轻松表达以下内容。

mutable struct Blockchain
    chain::Array{Dict{String, Any}}
    current_transactions::Array{String}
    block::Dict{String, Any}
    new_block::Function

    function Blockchain(chain::Array{Dict{String, Any}}, current::Array{String})    
        new(chain, current, new_block(previous_hash=1, proof=100)) 
        # ^issue calling function within the constructor here
    end
end

在这里,我假设您正在尝试向您的 struct 添加一些成员函数功能。 ,正如您已经说过的,您来自 C++背景。然而,这不是朱利安。在 Julia 中,正如 @crstnbr 已经建议的那样,我们需要定义作用于对象的全局函数。惯例是添加 !位于函数末尾,表示该函数将至少更改其参数之一。

然后,通过检查 new_block 的定义:

function new_block(proof::String, previous_hash::String=nothing)
    block = Dict(
    "index" => length(chain) + 1, # which chain?
    "timestamp" => time(),
    "transactions" => current_transactions, # which current_transactions?
    "proof" => proof,
    "previous_hash" => previous_hash | hash(chain[end]), # which chain?
    )
    current_transactions = []
    append!(chain, block) # which chain?
    return block
end

我注意到一些严重的错误。首先,您尝试使用一些 undefined variable ,例如 chaincurrent_transactions 。我假设,再次来自 C++ ,你有没有想过new_block将是 Blockchain 的成员函数,因此,可以看到chain成员变量。这不是Julia作品。第二个问题是你如何尝试调用 new_block :

new_block(previous_hash=1, proof=100)

这个调用完全错误。上面的调用符号依赖于 keyword arguments ;但是,您的函数定义具有位置参数。为了能够支持关键字参数,您需要将函数定义更改为如下所示:

function new_block(; proof::String, previous_hash::String=nothing)
  #                ^ note the semi-colon here
  # ...
end

最后,您定义 proofprevious_hash类型为String ,但是用 1 来称呼他们, 100nothing ,其类型为Int , IntVoid .

我无法理解您心中对区 block 链应用程序的设计选择,但我强烈建议您应该逐步使用更简单的示例来学习该语言。例如,如果您尝试以下示例,您将了解类型注释在 Julia 中的工作原理:

Main> f(s::String = nothing) = s
f (generic function with 2 methods)

Main> f()
ERROR: MethodError: no method matching f(::Void)
Closest candidates are:
  f(::String) at none:1
  f() at none:1
Stacktrace:
 [1] f() at ./none:1
 [2] eval(::Module, ::Any) at ./boot.jl:235

Main> g(s::String) = s
g (generic function with 1 method)

Main> g(100)
ERROR: MethodError: no method matching g(::Int64)
Closest candidates are:
  g(::String) at none:1
Stacktrace:
 [1] eval(::Module, ::Any) at ./boot.jl:235

Main> h1(var1 = 1, var2 = 100) = var1 + var2
h1 (generic function with 3 methods)

Main> h1(var2 = 5, var1 = 6)
ERROR: function h1 does not accept keyword arguments
Stacktrace:
 [1] kwfunc(::Any) at ./boot.jl:237
 [2] eval(::Module, ::Any) at ./boot.jl:235

最后一条评论是,据我从您的示例中看到,您不需要 mutable struct struct应该只是帮助您进行设计 --- 您仍然可以添加/修改其 chain , current_transactionsblock变量。再次检查下面更简单的示例:

Main> struct MyType
         a::Vector{Float64}
       end

Main> m = MyType([1,2,3]);

Main> append!(m.a, 4);

Main> m
MyType([1.0, 2.0, 3.0, 4.0])

你可以想到MyTypea变量,在上面的示例中为 double * const aC++条款。您不允许更改a指向不同的内存位置,但您可以修改 a 指向的内存位置.

简而言之,您绝对应该尝试从官方文档中逐步学习该语言,并在此处发布涉及真正最少示例的问题。从这个意义上说,你的例子很复杂。

关于function - 如何从 Julia 结构的构造函数中调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49216967/

相关文章:

javascript - .filter不是函数错误?

multithreading - Groovy:找不到匹配的构造函数 'subclass'

C++自定义迭代器构造函数

javascript - babel 编译 es6 类,函数未定义

javascript - 如何防止函数双重动画

ios - 我的导航 Controller 代码在 swift 中出现问题

Java:方法如何对未知类型的对象进行操作?

java - 我如何查看与 Clojure 中的对象关联的方法?

Java注解在注解声明中执行一个方法(用于android)

javascript - 设置超时函数