Note: started F# 4 days back so consider before giving a negative vote please. Or at least let me know what i am doing wrong to receive all the negative Votes.
Inteligence.fs
module Inteligence
open TTTAiFSharpAlphaBeta
open Boards
type Node(board: Board, moveBox :int, point:int)=
let mutable _moveBox:int=moveBox
let mutable _point:int=point
let mutable _board=new Board(board)
let mutable _parent= board
new() = Node(new Board(),0,0)
new(board: Board)= new Node(new Board(board),0,0)
member this.MoveBox with get() = _moveBox and set(value) = _moveBox <- value
member this.Point with get() = _point and set(value) = _point <- value
member this.Board with get() = _board and set(value) = _board <- value
member this.Parent with get() = _parent and set(value) = _parent <- value
member this.Copy(node: Node)=
_board<- new Board(node.Board)
_moveBox<- node.MoveBox
_point<- node.Point
_parent<- node.Parent
type Inteligence(board:Board,symbol:int)=
let mutable _nodeCount=0;
let mutable _rootNode= new Node(board)
let mutable _level = 0
let mutable _symbol = symbol
let mutable _reff = new Boards.Reffery()
member this.NodeCount with get() = _nodeCount and set(value) = _nodeCount <- value
member this.RootNode with get() = _rootNode and set(value) = _rootNode <- value
member this.Level with get() = _level and set(value) = _level <- value
member this.Symbol with get() = _symbol and set(value) = _symbol <- value
member this.Move() :int = 0
member this.MinMaxAlphaBeta(node:Node, min:bool, alpha:int, beta:int):int=0
member this.BoardPoint(node:Node):int=0
AI.fs
module TTTAiFSharpAlphaBeta
open AIInterface
open Boards
type AI()=
let mutable cboard =new Board()
let mutable level = 0
let mutable symbol = 0
interface IAI with
member this.SetAi (_board: Board ,_level, _symbol) =
cboard <- _board
level <- _level
symbol <- _symbol
member this.GetAiName()="F#AlphaBetaAi"
member this.GetAiVersion()="0.0.1"
member this.GetLevel()= [| 3 |];
member this.AiMove()=
Inteligence.Inteligence(cboard,symbol).Move()
The problem is i can't access
Move()
from Inteligence.fs
member this.AiMove()=
Inteligence.Inteligence(cboard,symbol).Move()
in AI.fs
Getting Error The namespace or module 'Inteligence' is not defined
What am i doing wrong?
I am guessing that you are using fsi (from the #r).
If you are you need to use
#load "Intelligence.fs"
If in visual studio you need to make sure Intelligence.fs is before the other file in the project list (F# is sensitive to the order files are compiled in)
Related
I try to making token lexical analyzer
and I want return Double type using map in scala
var m = Map[String,Double]()
def parseItem(tok: Tokenizer): Double = {
val startPos = tok.tokenPos
val t = tok.token
tok.next()
//(other codes)
else if (t.isIdentifier) {
var t1 = tok.token
if(t1.text == "=") {
tok.next()
var t2 = tok.token
if(t2.isNumber) {
m += (t.text -> t2.number)
println("Idenrifier sorted :" + t.text)
0
}else if(t2.isIdentifier && m.get(t2.text) == None){
println("Error!!! RHS is Wrong identifier!!!")
throw new SyntaxError(startPos, "expected number, identifier, or '('")
}else{
m += (t.text -> m.get(t2.text))
println("Idenrifier sorted :" + t.text)
0
}
}else{
m.get(t.text)
}
the error code is :Option[Double]
I think return type is Double But I can't understanding this error
m.get(t.text) is of type Option[Double]
You can use the apply method of the Map but keep in mind that the apply method returns the value associated with a given key directly, without wrapping it in an Option. If the key is not defined in the map, an exception is raised.
You can use m(t.text) or m.apply(t.text)
Or you can use m getOrElse (t.text, defaultValue) ,which returns the value associated with key t.text in the m map , or the defaultValue if not found.
Does anyone know how to implement red black trees with classes in OCaml?
At least the class properties and initializers? I'm new in OCaml.
What I tried:
type data = {key: int; value: string}
class node (data: data) =
object (self)
val mutable d = data
val mutable color = 1
val mutable left = ref (None: node option)
val mutable right = ref (None: node option)
val mutable parent = ref (None: node option)
method getLeft = left
method getRight = right
method getParent = parent
method getColor = color
method getData = d
method setLeft (l: node option ref) = left := !l
method setRight (l: node option ref) = right := !l
method setParent (l: node option ref) = parent := !l
end;;
class rbtree =
object (self)
val mutable root = ref (None: node option)
val mutable nullNode = ref (None: node option)
method searchNode (aNode: node option ref) (key: data) = begin
if aNode = nullNode || key == (!aNode)#getData then aNode;
end;
end;;
I get the error This expression has type node option
It has no method getData
What I am trying is to make something like this code that is written in C++:
struct Node
{
int data;
Node *parent;
Node *left;
Node *right;
int color;
};
typedef Node *NodePtr;
class RedBlackTree
{
private:
NodePtr root;
NodePtr TNULL;
void initializeNULLNode(NodePtr node, NodePtr parent)
{
node->data = 0;
node->parent = parent;
node->left = nullptr;
node->right = nullptr;
node->color = 0;
}
NodePtr searchTreeHelper(NodePtr node, int key)
{
if (node == TNULL || key == node->data)
{
return node;
}
if (key < node->data)
{
return searchTreeHelper(node->left, key);
}
return searchTreeHelper(node->right, key);
}
};
For the error you're seeing, #Shon is correct. You have this expression:
if aNode = nullNode || key == (!aNode)#getData then aNode;
The type of aNode is node option ref. So that means the type of !anode is node option. An option value isn't an object (an instance of a class). So you can't call the method getData on it.
Again, as #Shon says, you need to retrieve the value of !aNode (if there is one). This will give you a node, which is an object and does have a getData method.
It would be messy to write this code in-line in your if test. So you might write a function like this:
let node_option_has_value node_opt value =
match node_opt with
| None -> false
| Some node -> node#getData = value
As a side comment, you should not be using the physical equality operator (==) to do comparisons. This operator is for special cases, not for general use.
The equality comparison operator in OCaml is = (as in my example code).
Simple question: In the following generic class, how should the generic type and contained types be defined so that they are nullable? The following will not compile.
class Pair? of G1, G2: Object
_first:G1?
_second:G2?
construct()
_first = null
_second = null
def insert( first:G1, second:G2 )
_first = first
_second = second
def insert_first( value:G1 )
_first = value
def insert_second( value:G2 )
_second = value
def second():G2
return _second
Usage:
var pair = new Pair() of string, string
pair = null
Due to the way Vala Generics work, generic parameters are always nullable.
As long as you don't switch on --enable-experimental-non-null class variables are nullable as well, so your code simplifies to:
[indent=4]
class Pair of G1, G2: Object
_first:G1
_second:G2
construct()
_first = null
_second = null
def insert( first:G1, second:G2 )
_first = first
_second = second
def insert_first( value:G1 )
_first = value
def insert_second( value:G2 )
_second = value
def second():G2
return _second
init
var pair = new Pair of string, string
pair = null
When --enable-experimental-non-null is on, you have to be explicit in the type of the variable. I don't know how to write this in Genie, I tried this, but the compiler does not like it:
init
pair: Pair? of string, string = new Pair of string, string
pair = null
In Vala it's no problem:
class Pair<G1,G2>: Object {
private G1 first;
private G2 second;
public Pair () {
first = null;
second = null;
}
// ...
}
int main () {
Pair<string, string>? pair = new Pair<string, string> ();
pair = null;
return 0;
}
I can't wrap my head around the concept of a type parameter that has null as the type. I don't think that is a useful concept. So the definition of your class would be:
[indent = 4]
class Pair of G1, G2: Object
_first:G1?
_second:G2?
def insert( first:G1, second:G2 )
_first = first
_second = second
def insert_first( value:G1 )
_first = value
def insert_second( value:G2 )
_second = value
def second():G2
return _second
If you must re-assign the variable that has the object instance to null then it would be:
[indent = 4]
init
var pair = new Pair of string,string()
pair = null
The Vala compiler will, however, dereference pair when it goes out of scope. So I'm not sure why you would need to assign null.
The use of nulls would ideally only be used when interfacing with a C library in my view. Accessing a null can lead to a crash (segmentation fault) if it is not checked for properly. For example:
init
a:int? = 1
a = null
var b = a + 1
The Vala compiler does have an experimental non-null mode that does some checking for unsafe code. If you compile the following with the Vala switch --enable-experimental-non-null:
[indent = 4]
init
var pair = new Pair of string,string()
pair = null
you will get the error:
error: Assignment: Cannot convert fromnull' to Pair<string,string>'
If you understand the consequences then you can tell the compiler this is OK with:
[indent = 4]
init
pair:Pair? = new Pair of string,string()
pair = null
Following is a simple map entry assignment:
scala> var myl = mutable.Map[String,String]()
myl: scala.collection.mutable.Map[String,String] = Map()
myl("abc") = "123"
I would like to mimic that assignment structure in my own class that works with mutable Tuple's. Now, "getting" a value from a Map is achieved via the "apply" method:
e.g mutable.HashMap:
override def apply(key: A): B = {
val result = findEntry(key)
if (result eq null) default(key)
else result.value
}
I was not however able to find how the map entry is "set" via myMap("myKey") = "myval". A pointer to the Scala source code to do that would be appreciated. Thanks.
The method you want to implement is called update() and takes two parameters, one for the input value passed in parentheses and the other for the assigned value.
class QueryParams {
var params = ""
def update(name: String, value: String) { params += s"$name=$value&" }
}
For example:
val p = new QueryParams()
p("q") = "SFO"
p("start") = "10"
p("rows") = "10"
p.params
I'm currently learning Scala, and just discovered the way to create custom field getters/setters. I have a simple example working:
class Thing(private val a:Int){
override def toString = "Thing[" + a + "]"
private var _value = a
def value = _value
def value_= (newVal:Int) = _value = newVal
}
On the console I can do:
scala> var t = new Thing(2)
t: dylan.code.Thing = Thing[2]
scala> t.value
res1: Int = 2
scala> t.value = 3
scala> t.value
res2: Int = 3
Now I'm trying to bring this concept to a slightly more complicated example; I'll try to whittle the code down to what's relevant:
abstract class CellExpression[Type] extends Publisher[CellUpdateEvent[Type]] with Subscriber[CellUpdateEvent[Type], CellExpression[Type]]{
protected var cachedValue: Type = recalculateValue()
protected def recalculateValue(): Type
protected def changeValue(newValue: Type):Unit = {
val oldValue = value()
if(newValue != oldValue){
cachedValue = newValue
publish(new CellUpdateEvent(this, oldValue, newValue))
}
}
def value() = cachedValue
def notify(pub: CellExpression[Type], event: CellUpdateEvent[Type]) = changeValue(recalculateValue())
}
//....
class CellVariable[Type](private val initialValue:Type) extends CellExpression[Type]{
cachedValue = initialValue
protected def recalculateValue() = { cachedValue }
override def toString = "CellVariable[" + value + "]"
def value_= (newValue:Type) = {changeValue(newValue)}
}
As far as I can tell, I've done what I need to in order to be able to treate value as a field via its getter and setter. But when I try it out in the console, I get:
scala> var i = new CellVariable(2)
i: dylan.code.CellVariable[Int] = CellVariable[2]
scala> i.value = 3
<console>:11: error: reassignment to val
i.value = 3
^
What have I done wrong, and how can I fix it?
I actually stumbled onto the solution.
The line where I declare my value function: def value() = cachedValue is the culprit.
If I remove the parentheses to make the line def value = cachedValue everything seems to work as I expected.
You cannot change values in Scala. A value is assigned once and only once. If you want to do this then you need to use variables instead of values. In other words, change the declaration from val to var.
The problem is inside one of your class definitions and may be on a line without val because I believe that if you neglect to declare a name, then Scala assumes that it is a value and therefore immutable.
Not sure what you want getters and setters for though. Scala enables you to ignore all of that Java overhead.
It is probably the line that says cachedValue = initialValue because it is not declared with var anywhere in that class. The definition in the other class is a different name because it is in a different scope. You would have to say something like class.varname to change a variable defined in another class.