在F#中创建自定义类型的列表,并创建该列表的两个序列 [英] Create a list of custom type in F# and create two sequences of that list
问题描述
我已经在F#中创建了自己的类型,称为帐户",然后为每个帐户创建了对象.
I have created my own type in F# called Accounts and I have then created objects for each account.
type Account() =
let AccountNumber = ""
let mutable Balance:float = 0.0
每个帐户都有两个字段,AccountNumber(字符串)和Balance(浮动).
Every account has two fields, AccountNumber (string) and Balance (float).
然后,我为每个拥有AccountName和Balance的帐户创建了一个对象.
I have then created an object for every account that holds the AccountName and the Balance.
let acc1 = new Account()
acc1.Insert("John",10.0)
let acc2 = new Account()
acc2.Insert("Mike",50.0)
如何创建一个包含每个帐户(对象)的列表?我尝试了以下方法:
How do I create a list that holds each account (object)? I have tried the following:
let AccountList : Account list = [acc1; acc2 ; acc3; acc4 ; acc5; acc6]
let AccountList : Account obj list = [acc1; acc2 ; acc3; acc4 ; acc5; acc6]
我无法使用上述方法解决问题,因为我必须从列表中创建两个序列:
I cannot solve the problem using the above method because I have to create two sequences from the list:
顺序1:所有余额大于或等于零且小于50的帐户 顺序2:余额大于50的所有帐户
Sequence 1: All accounts with a balance greater or equal to zero and less than 50 Sequence 2: All accounts with a balance above 50
如何在F#中创建自定义类型的列表,以及如何创建该列表的两个序列?
How do I create a list of my custom type in F# and how do I create two sequences of that list?
推荐答案
目前尚不清楚您到底在挣扎什么.但是,以下简单示例应说明您可能需要使用的大多数关键思想.首先,这是您的Account
类的一个小版本(请注意,我通常会使用不可变的记录,但我会按照您的记录方式进行保存):
It is not clear what exactly are you struggling with. However, the following simple example should illustrate most of the key ideas that you probably need to use. First, here is a small version of your Account
class (note that I would normally use an immutable record, but I kept it the way you did it):
type Account(balance:float) =
let mutable balance = balance
member x.Balance = balance
member x.Add(difference) =
balance <- balance + difference
我看不到创建列表有什么问题.以下工作正常:
I do not see what issue you have with creating the list. The following works just fine:
let acc1 = Account(100.0)
let acc2 = Account(10.0)
let accountList = [acc1; acc2]
现在,要回答有关查找余额超过50的帐户的问题,可以使用List.filter
函数来创建新的过滤列表:
Now, to answer the question about finding accounts with balance over 50, you can use the List.filter
function to create a new filtered list:
let above50 =
accountList |> List.filter (fun acc ->
acc.Balance > 50.0)
编辑,如果您想使用记录,则可以将类型定义为:
EDIT If you wanted to use a record instead, then you would define the type as:
type Account = { Balance : float }
并使用以下方法创建值:
And create a value using:
let acc1 = { Balance = 100.0 }
这篇关于在F#中创建自定义类型的列表,并创建该列表的两个序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!