PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 19, 2022

[FIXED] how to call a function to another function in julia?

 October 19, 2022     function, julia     No comments   

Issue

I am writing a code in julia but I am unable to call a function from another function. Code is:

function add(x, y)
    if x == 3 && y ==1
        z =0
    else x == 0 && y ==0
        z =1
    end
    return z
end

function width(a, b, c)
    add(x,y)
    .....
end

The variables in add function will be used in width function but as I am new to julia, I am unable to call add in the other function. Kindly guide. Edit: I tried declaring with the z but it also didn't worked

struct z 
    a::Int 
    b::Int 
end

Solution

There are two problems in your code that are not related to Julia per se. First problem in the add function: if x == 3 && y == 1 the output should be z = 0, else if x == 0 && y == 0, actually the if was missing, the output should be z = 1. Now what will be the output if, e.g., x = 1 && y == 1? The answer is nothing and z will be undefined.

To fix the add function, you should add a default branch for the if-else.

function add(x, y)
    if x == 3 && y == 1
        z = 0
    elseif x == 0 && y == 0
        z = 1
    else 
        z = -1 # some default
    end
    return z
end

The same function could be written more concisely as:

function add(x, y)
    x == 3 && y == 1 && return 0
    x == 0 && y == 0 && return 1
    return -1 # some default
end

which can even be written in a one-liner like this:

add(x, y) = x == 3 && y == 1 ? 0 : x == 0 && y == 0 ? 1 : -1 # some default

The second problem is with the width function. x and y are not defined inside the body of the width function. So, you can't call add(x, y). It should be z = add(a, b) where z should be used in subsequent calculations. Finally, check what the third argument c is for, otherwise, remove it.

function width(a, b, c)
    z = add(a, b)
    .....
end


Answered By - AboAmmar
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing