I am going through Parallel Loops and Maps and I am seeming to have difficulty with even accessing the file count_heads.jl
I saved it in my working directory
function count_heads(n)
c::Int = 0
for i = 1:n
c += rand(Bool)
end
c
end
And I can verify it's existence in that directory:
filter(r"count_heads.jl", readdir())
#1-element Array{String,1}:
#"count_heads.jl"
Yet when I attempt the next step in the tutorial.
#everywhere include_string(Main, $(read("count_heads.jl", String)), "count_heads.jl")
ERROR: MethodError: Cannot `convert` an object of type Type{String} to an object of type Array{UInt8,1}
This may have arisen from a call to the constructor Array{UInt8,1}(...),
since type constructors fall back to convert methods.
Looking at just the read("count_heads.jl", String) function I get the source of the error (I think).
You are probably using an older version of Julia (Julia 0.5?). read(filename, String) requires Julia 0.6 or later (https://github.com/JuliaLang/julia/issues/22793).
Related
I have code that produced a circular build error, and I looked up the error. This page gives a similar but smaller example of what's in my .mli file: https://ocaml.org/learn/tutorials/ocamlbuild/New_kinds_of_build_errors.html
Essentially the problem is that my file is both defining a type and defining functions that use arguments and return values of that same type. However, that's exactly what I want my program to do. My type is not private, it's declared explicitly in the .mli file:
type state = {
current_pos : int*int;
contents : int*int list;
}
val update_state : state -> state
It seems to me reasonable to want to build a module that defines a type and then to share that type with other files, but it seems like the circular build error will always prevent that. Is there some "more proper" way of doing this sharing?
There's nothing at all wrong with the code you posted. It compiles fine. So the problem is in your .ml file.
The page you point to shows code that is incorrect. The only point being made is that you'll get a different error if you use ocamlbuild than you would if you just compile the file directly.
The key point is that you should not use the name of a module inside the definition of the module.
Instead of this (in a.ml):
type t = int
let x : A.t = 14
You should have this:
type t = int
let x: t = 14
If your code is really like this example, you just need to remove the module names inside the .ml file.
As you say, what you want to do is by far the most common use of a module.
I would like to do dynamic casting for a scala variable, the casting type is stored in a different variable or in the database or provided by the user.
I am new to Scala and have mainly done coding on python. Here we are trying to take Any type input and query the type of the variable as per the type saved in DB eg.: "String/Int" and user-defined classes and cast them before any future processing.
in python:
eval("str('123')")
in scala I have tried
var a = 123.05
a.asInstanceOf['Int']
gives me error
error: identifier expected but string literal found.
And I want the code to be something as follows:
var a = 123.05
var b = "Int"
a.asInstanceOf[b]
gives me error
error: not found: type b
Ok so I have to be fairly exhaustive here because the stuff you're trying to do is tricky due to the static vs dynamic typing difference of scala and python.
First what you're doing in Python is not type casting but rather a conversion.
str(12)
in python takes the integer value 12 and converts it to a (UTF-8 ? dunno in python) string. The same thing in scala would be
12.toString
typecasting in the meantime is basically a pinky promise to the compilers typechecker that you know more than it and it should just believe you. It also should be avoided like the pest because you basically drop all the safety that static typechecking gives you. However there are certain cases where it is unavoidable
in a bit more fundamental terms. lets say you have the following scala snippet
sealed trait Foo
final case class Bar(i:Int) extends Foo
final case class Baz(s:String) extends Foo
val f:Foo = Bar(2)
//won't work because the compiler thinks f is of type Foo due to the type ascription bove
println(f.i)
//will work
println(f.asInstanceOf[Bar].i)
the Type Foo can be either Bar or Baz (because of the sealed and final, this is called an ADT) but we specifically told the compiler to treat f as a Foo which means we forgot which specific type it was. this is the case where you could use typecasting, note that we don't convert but rather tell the compiler that it is actually a Bar
Now this all happens during compile time which means you can't cast according to a runtime value like this
var a = 123.05
var b = "Int"
a.asInstanceOf[b]
Now as I understand you have some sort of stringly typed input and need to convert it according to some schema. The scalafiddle below has an example how you could do this: https://scalafiddle.io/sf/i97WZlA/0
However note that this makes use of some fairly advanced concepts in scala to ensure the types line up.
This will also work https://scalafiddle.io/sf/i97WZlA/1 but note that we lose all the type information requiring us to do a typecast if we want to do anything meaningful with out
EDIT/ADDENDUM: I thought I should also do an example on how to consume such values and make the schema dynamic.
https://scalafiddle.io/sf/i97WZlA/2
As a final note be warned that this is getting close to the limits what the compiler can do and necessitates a lot of boxing and unboxing to carry along the type information (in SchemaValue) also it's not stacksafe and has lackluster errorhandling. this solution would require some serious engineering to make viable but it should get the idea across
If you have a String value, then you can use toInt or toDouble to parse that string:
val s = "123.05"
val i = s.toInt
val d = s.toDouble
If you have an Any value then it is best to use match to convert it:
val a: Any = ...
a match {
case i: Int => // It is an Int
case d: Double => // It is a Double
case _ => // It is a different type
}
If all else fails you can explicitly pick a type, but this is not good practice:
val i = a.asInstanceOf[Int]
Any decent database framework will give you the ability to read and write values of specific types, so this should not be a problem with the right library.
I'm trying to call the max function: max(x: T, y: T). However I keep getting the following error when I type max(2,3):
error: cannot call value of non-function type Int
var a = max(2, 3)
I am a beginner, and I have never encountered a function signature that uses a type "T". SO threads relating to using the max function call it in the manner I am (like max(2,3) ) so I am not sure where I am going wrong.
I am looking for an explanation on the "T" and how to call functions that support generic types and how to make the max function return 3 when comparing integers 2 and 3.
The problem (as you've confirmed in the comments) is that you have defined a variable named max, causing a naming conflict with the function max(_:_:).
The solution therefore is to either specify the Swift module namespace (as George suggested) in order to disambiguate the fact that you're referring to the max(_:_:) function:
Swift.max(2, 3)
Or, preferably, you should consider renaming your variable. I strongly suspect that there's a more descriptive name you could give it (remember, the Swift API Design Guidelines favours clarity over brevity).
Are you calling max within extension Int?
Try Swift.max(2, 3).
I'm playing around trying to understand classes in Haskell.
I wrote a silly few lines of code to get the hang of it. I wrote a class called Slang that has one function. When I make Integer an instance of my class, it works fine. But when I make String an instance of my class it won't compile. I've been fidgeting with the program based on what the error output tells me but to no avail. I have idea why it work...
Here is the code followed by the error:
module Practice where
class Slang s where
slangify :: s -> String
instance Slang Integer where
slangify int = "yo"
instance Slang String where -- When I take this segment out, it works fine
slangify str = "bro"
ERROR:
Prelude> :load Practice
[1 of 1] Compiling Practice ( Practice.hs, interpreted )
Practice.hs:9:10:
Illegal instance declaration for `Slang String'
(All instance types must be of the form (T t1 ... tn)
where T is not a synonym.
Use -XTypeSynonymInstances if you want to disable this.)
In the instance declaration for `Slang String'
Failed, modules loaded: none.
Prelude>
The problem is that String is not a base type like Integer. What you are trying to do is actually
instance Slang [Char] where
slangify str = "bro"
However, Haskell98 forbids this type of typeclass in order to keep things simple and to make it harder for people to write overlapping instances like
instance Slang [a] where
-- Strings would also fit this definition.
slangify list = "some list"
Anyway, as the error message suggests, you can get around this restriction by enabling the FlexibleInstances extension.
I did some research in my Haskell literature (aka my current Bible) and found an example that effectively solves my problem.
Basically, in this workaround you set Char to be an instance of the class (in the book's example it's called Visible) and then you can set [chars] aka a String, to be an instance of the class as well ONLY WITH the stipulation that the type variable chars be an instance of `Visible'.
It's easier to understand if you look at the code below:
module Practice where
class Visible a where
toString :: a -> String
size :: a -> Int
instance Visible Char where
toString ch = [ch]
size _ = 1
instance Visible a => Visible [a] where
toString = concat . map toString
size = foldr (+) 1 . map size
My GHCi load and function call:
*Practice> :l Practice
[1 of 1] Compiling Practice ( Practice.hs, interpreted )
Ok, modules loaded: Practice.
*Practice> size "I love Stack!"
14
*Practice>
Eureka!
While writing a library to read image values, I have the following problem:
I defined a new type called realimage. Within this type a function is referenced, which returns an array as a result.
module typedefinition
implicit none
type realimage
integer :: byteorder = 0
contains
procedure :: initialize => initializereal
procedure :: pxvalues => pxvaluesreal ! Array valued function
end type realimage
contains
function pxvaluesreal(this, x, y) result(val)
implicit none
type(realimage) this
real val(5)
integer :: x, y
...
end function
end module
Compiling the module with gfortran and calling the function with image1%pxvalues(x,y), I always get the following error message:
main.f95: In function ‘testtype’:
main.f95:15: internal compiler error
If I directly call the function in the main program (pxvaluesreal(image1,x,y)), everything works fine.
Is it possible to define the array dimension in the type definition in order to tell the compiler, which are the dimesions of the return value of the function?
Internal compiler errors are always due to a compiler bug. If you are using a recent version of gfortran you should consider reviewing their list of open bugs and perhaps filing a bug report.
Beyond that - your code is not standard compliant - the passed object 'this' must be polymorphic (declare it with CLASS rather than TYPE). Otherwise your specification of the size of the array function result is correct - when you reference the pxvalues binding the compiler knows that the size of the function result is 5 as it 'knows' the interface of the specific procedure pxvaluesreal that the binding is associated with.