- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想以最惯用的方式实现以下内容
玩家在 map 上。
open System
[<AbstractClass>]
type ActorBase(x,y,symbol)=
member this.X:int=x
member this.Y:int=y
member this.Symbol:char=symbol
type Medication(x,y)=
inherit ActorBase(x,y,'♥')
type Coin(x,y)=
inherit ActorBase(x,y,'$')
type Arrow(x,y,symbol,targetX,targetY) =
inherit ActorBase(x,y,symbol)
member this.TargetX=targetX
member this.TargetY=targetY
[<AbstractClass>]
type CreatureBase(x,y,symbol,hp) =
inherit ActorBase(x,y,symbol)
member this.HP:int=hp
type Player(x,y,hp, score) =
inherit CreatureBase(x,y,'@',hp)
member this.Score = score
type Zombie(x,y,hp,targetX,targetY) =
inherit CreatureBase(x,y,'z',hp)
member this.TargetX=targetX
member this.TargetY=targetY
let playerInteraction (player:Player) (otherActor:#ActorBase):unit =
printfn "Interacting with %c" otherActor.Symbol
match (otherActor :> ActorBase) with
| :? CreatureBase as creature -> printfn "Player is hit by %d by creature %A" (creature.HP) creature
| :? Arrow -> printfn "Player is hit by 1 by arrow"
| :? Coin -> printfn "Player got 1$"
| :? Medication -> printfn "Player is healed by 1"
| _ -> printfn "Interaction is not recognized"
let otherActorsWithSamePosition (actor:#ActorBase) =
seq{
yield new Zombie(0,0,3,1,1) :> ActorBase
yield new Zombie(0,1,3,1,1) :> ActorBase
yield new Arrow(0,0,'/',1,1) :> ActorBase
yield new Coin(0,0) :> ActorBase
yield new Medication(0,0) :> ActorBase
}
|> Seq.where(fun a -> a.X=actor.X && a.Y=actor.Y)
[<EntryPoint>]
let main argv =
let player = new Player(0,0,15,0)
for actor in (otherActorsWithSamePosition player) do
playerInteraction player actor
Console.ReadLine() |> ignore
0
otherActorsWithSamePosition
?实现
otherXsWithSamePosition
每个类(class)
X
从 Actor 派生看起来不像可扩展的解决方案
type IActor =
abstract member X:int
abstract member Y:int
abstract member Symbol:char
type IDamagable =
abstract member Damaged:int->unit
type IDamaging =
abstract member Damage:int
type Player =
{
X:int
Y:int
HP:int
Score:int
}
interface IActor with
member this.X=this.X
member this.Y=this.Y
member this.Symbol='@'
interface IDamagable with
member this.Damaged damage = printfn "The player is damaged by %d" damage
interface IDamaging with
member this.Damage = this.HP
type Coin =
{
X:int
Y:int
}
interface IActor with
member this.X=this.X
member this.Y=this.Y
member this.Symbol='$'
type Medication =
{
X:int
Y:int
}
interface IActor with
member this.X=this.X
member this.Y=this.Y
member this.Symbol='♥'
type Arrow =
{
X:int
Y:int
DestinationX:int
DestinationY:int
Symbol:char
}
interface IActor with
member this.X=this.X
member this.Y=this.Y
member this.Symbol=this.Symbol
interface IDamaging with
member this.Damage = 1
type Zombie =
{
X:int
Y:int
DestinationX:int
DestinationY:int
HP:int
}
interface IActor with
member this.X=this.X
member this.Y=this.Y
member this.Symbol='z'
interface IDamaging with
member this.Damage = this.HP
type Actor =
|Player of Player
|Coin of Coin
|Zombie of Zombie
|Medication of Medication
|Arrow of Arrow
let otherActorsWithSamePosition (actor:Actor) =
seq{
yield Zombie {X=0;Y=0; HP=3;DestinationX=1;DestinationY=1}
yield Zombie {X=0;Y=1; HP=3;DestinationX=1;DestinationY=1}
yield Arrow {X=0;Y=0; Symbol='/';DestinationX=1;DestinationY=1}
yield Coin {X=0;Y=0}
yield Medication {X=0;Y=0}
}
//Cannot cast to interface
|> Seq.where(fun a -> (a:>IActor).X=actor.X && (a:>IActor).Y=actor.Y)
let playerInteraction player (otherActor:Actor) =
match otherActor with
| Coin coin -> printfn "Player got 1$"
| Medication medication -> printfn "Player is healed by 1"
//Cannot check this
| :?IDamaging as damaging -> (player:>IDamagable).Damaged(damaging.Damage)
[<EntryPoint>]
let main argv =
let player = Player {X=0;Y=0;HP=15;Score=0}
for actor in (otherActorsWithSamePosition player) do
playerInteraction player actor
Console.ReadLine() |> ignore
0
Actor =
| Medication {x:int;y:int;symbol:char}
type Medication = {x:int;y:int;symbol:char}
Actor =
| Medication
Medication
和
Actor.Medication
不同种类
type Medication = {x:int;y:int;symbol:char}
Actor =
| Medication of Medication
最佳答案
Is pattern matching on derived types idiomatic for F#?
Are classes and inheritance meant to be used in F#?
Or are they just for compatibility with .Net?
When to Use Classes, Unions, Records, and Structures
你会看见
Given the variety of types to choose from, you need to have a good understanding of what each type is designed for to select the appropriate type for a particular situation. Classes are designed for use in object-oriented programming contexts. Object-oriented programming is the dominant paradigm used in applications that are written for the .NET Framework. If your F# code has to work closely with the .NET Framework or another object-oriented library, and especially if you have to extend from an object-oriented type system such as a UI library, classes are probably appropriate.
If you are not interoperating closely with object-oriented code, or if you are writing code that is self-contained and therefore protected from frequent interaction with object-oriented code, you should consider using records and discriminated unions. A single, well thought–out discriminated union, together with appropriate pattern matching code, can often be used as a simpler alternative to an object hierarchy. For more information about discriminated unions, see Discriminated Unions (F#).
Should I use records instead, and, if yes, how?
it depends
问题。
Records have the advantage of being simpler than classes, but records are not appropriate when the demands of a type exceed what can be accomplished with their simplicity. Records are basically simple aggregates of values, without separate constructors that can perform custom actions, without hidden fields, and without inheritance or interface implementations. Although members such as properties and methods can be added to records to make their behavior more complex, the fields stored in a record are still a simple aggregate of values. For more information about records, see Records (F#).
Structures are also useful for small aggregates of data, but they differ from classes and records in that they are .NET value types. Classes and records are .NET reference types. The semantics of value types and reference types are different in that value types are passed by value. This means that they are copied bit for bit when they are passed as a parameter or returned from a function. They are also stored on the stack or, if they are used as a field, embedded inside the parent object instead of stored in their own separate location on the heap. Therefore, structures are appropriate for frequently accessed data when the overhead of accessing the heap is a problem. For more information about structures, see Structures (F#).
Switching on types is considered a bad practice in C#. Is it the same for F#?
Is pattern matching on derived types idiomatic for F#?
的答案
How?
namespace Game
type Location = int * int
type TargetLocation = Location
type CurrentLocation = Location
type Symbol = char
type ActorType = CurrentLocation * Symbol
type HitPoints = int
type Health = int
type Money = int
type Creature = ActorType * HitPoints
// Player = Creature * Health * Money
// = (ActorType * HitPoints) * Health * Money
// = ((CurrentLocation * Symbol) * HitPoints) * Health * Money
// = ((Location * Symbol) * HitPoints) * Health * Money
// = (((int * int) * char) * int) * int * int
type Player = Creature * Health * Money
type Actor =
| Medication of ActorType
| Coin of ActorType
| Arrow of Creature * TargetLocation // Had to give arrow hit point damage
| Zombie of Creature * TargetLocation
module main =
[<EntryPoint>]
let main argv =
let player = ((((0,0),'p'),15),0,0)
let actors : Actor List =
[
Medication((0,0),'♥');
Zombie((((3,2),'Z'),3),(0,0));
Zombie((((5,1),'Z'),3),(0,0));
Arrow((((4,3),'/'),3),(2,1));
Coin((4,2),'$');
]
let updatePlayer player (actors : Actor list) : Player =
let interact (((((x,y),symbol),hitPoints),health,money) : Player) otherActor =
match (x,y),otherActor with
| (playerX,playerY),Zombie((((opponentX,opponentY),symbol),zombieHitPoints),targetLocation) when playerX = opponentX && playerY = opponentY ->
printfn "Player is hit by creature for %i hit points." zombieHitPoints
((((x,y),symbol),hitPoints - zombieHitPoints),health,money)
| (playerX,playerY),Arrow((((opponentX,opponentY),symbol),arrowHitPoints),targetLocation) when playerX = opponentX && playerY = opponentY ->
printfn "Player is hit by arrow for %i hit points." arrowHitPoints
((((x,y),symbol),hitPoints - arrowHitPoints),health,money)
| (playerX,playerY),Coin((opponentX,opponentY),symbol) when playerX = opponentX && playerY = opponentY ->
printfn "Player got 1$."
((((x,y),symbol),hitPoints),health,money + 1)
| (playerX,playerY),Medication((opponentX,opponentY),symbol) when playerX = opponentX && playerY = opponentY ->
printfn "Player is healed by 1."
((((x,y),symbol),hitPoints),health+1,money)
| _ ->
// When we use guards in matching, i.e. when clause, F# requires a _ match
((((x,y),symbol),hitPoints),health,money)
let rec updatePlayerInner player actors =
match actors with
| actor::t ->
let player = interact player actor
updatePlayerInner player t
| [] -> player
updatePlayerInner player actors
let rec play player actors =
let player = updatePlayer player actors
play player actors
// Since this is example code the following line will cause a stack overflow.
// I put it in as an example function to demonstrate how the code can be used.
// play player actors
// Test
let testActors : Actor List =
[
Zombie((((0,0),'Z'),3),(0,0))
Arrow((((0,0),'/'),3),(2,1))
Coin((0,0),'$')
Medication((0,0),'♥')
]
let updatedPlayer = updatePlayer player testActors
printf "Press any key to exit: "
System.Console.ReadKey() |> ignore
printfn ""
0 // return an integer exit code
Player is hit by creature for 3 hit points.
Player is hit by arrow for 3 hit points.
Player got 1$.
Player is healed by 1.
关于types - 派生类型的模式匹配对于 F# 来说是惯用的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36529293/
我正在尝试编写一个相当多态的库。我遇到了一种更容易表现出来却很难说出来的情况。它看起来有点像这样: {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE
谁能解释一下这个表达式是如何工作的? type = type || 'any'; 这是否意味着如果类型未定义则使用“任意”? 最佳答案 如果 type 为“falsy”(即 false,或 undef
我有一个界面,在IAnimal.fs中, namespace Kingdom type IAnimal = abstract member Eat : Food -> unit 以及另一个成功
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: What is the difference between (type)value and type(va
在 C# 中,default(Nullable) 之间有区别吗? (或 default(long?) )和 default(long) ? Long只是一个例子,它可以是任何其他struct类型。 最
假设我有一个案例类: case class Foo(num: Int, str: String, bool: Boolean) 现在我还有一个简单的包装器: sealed trait Wrapper[
这个问题在这里已经有了答案: Create C# delegate type with ref parameter at runtime (1 个回答) 关闭 2 年前。 为了即时创建委托(dele
我正在尝试获取图像的 dct。一开始我遇到了错误 The function/feature is not implemented (Odd-size DCT's are not implemented
我正在尝试使用 AFNetworking 的 AFPropertyListRequestOperation,但是当我尝试下载它时,出现错误 预期的内容类型{( “应用程序/x-plist” )}, 得
我在下面收到错误。我知道这段代码的意思,但我不知道界面应该是什么样子: Element implicitly has an 'any' type because index expression is
我尝试将 SignalType 从 ReactiveCocoa 扩展为自定义 ErrorType,代码如下所示 enum MyError: ErrorType { // .. cases }
我无法在任何其他问题中找到答案。假设我有一个抽象父类(super class) Abstract0,它有两个子类 Concrete1 和 Concrete1。我希望能够在 Abstract0 中定义类
我想知道为什么这个索引没有用在 RANGE 类型中,而是用在 INDEX 中: 索引: CREATE INDEX myindex ON orders(order_date); 查询: EXPLAIN
我正在使用 RxJava,现在我尝试通过提供 lambda 来订阅可观察对象: observableProvider.stringForKey(CURRENT_DELETED_ID) .sub
我已经尝试了几乎所有解决问题的方法,其中包括。为 提供类型使用app.use(express.static('public'))还有更多,但我似乎无法为此找到解决方案。 index.js : imp
以下哪个 CSS 选择器更快? input[type="submit"] { /* styles */ } 或 [type="submit"] { /* styles */ } 只是好
我不知道这个设置有什么问题,我在 IDEA 中获得了所有注释(@Controller、@Repository、@Service),它在行号左侧显示 bean,然后转到该 bean。 这是错误: 14-
我听从了建议 registering java function as a callback in C function并且可以使用“简单”类型(例如整数和字符串)进行回调,例如: jstring j
有一些 java 类,加载到 Oracle 数据库(版本 11g)和 pl/sql 函数包装器: create or replace function getDataFromJava( in_uLis
我已经从 David Walsh 的 css 动画回调中获取代码并将其修改为 TypeScript。但是,我收到一个错误,我不知道为什么: interface IBrowserPrefix { [
我是一名优秀的程序员,十分优秀!