首页 \ 问答 \ F#树:节点插入(F# Tree: Node Insertion)

F#树:节点插入(F# Tree: Node Insertion)

这是一个扩展F#递归树验证的问题 ,我昨天很好地回答了这个问题。

这个问题涉及在现有树中插入一个孩子。 这是我想要使用的更新类型:

type Name           = string
type BirthYear      = int
type FamilyTree     = Person of Name * BirthYear * Children
and Children        = FamilyTree list

我的最后一个问题是关于检查树的有效性,这是我决定采用的解决方案:

let rec checkAges minBirth = function
    | Person(_,b,_) :: t -> b >= minBirth && checkAges b t
    | [] -> true

let rec validate (Person(_,b,c)) =
    List.forall isWF c && checkAges (b + 16) c

现在我希望能够以下列形式插入一个人Simon作为特定人汉族的孩子

insertChildOf "Hans" simon:Person casperFamily:FamilyTree;;

因此,输入应该是父家谱 。 理想情况下,它应该返回一个修改后的族树,即FamilyTree选项

我正在努力的是合并验证函数以确保它是合法的,并且如果插入Person已经是父级,则可以将其正确地插入到子级列表中 - 可能作为单独的函数。

欢迎所有帮助,非常感谢 - 谢谢! :)


This is a question that extends F# Recursive Tree Validation, which I had nicely answered yesterday.

This question concerns inserting a child in an existing tree. This is the updated type I'd like to use:

type Name           = string
type BirthYear      = int
type FamilyTree     = Person of Name * BirthYear * Children
and Children        = FamilyTree list

My last question concerned checking the validity of the tree, this was the solution I decided to go with:

let rec checkAges minBirth = function
    | Person(_,b,_) :: t -> b >= minBirth && checkAges b t
    | [] -> true

let rec validate (Person(_,b,c)) =
    List.forall isWF c && checkAges (b + 16) c

Now I would like to be able to insert a Person Simon as a child of specific Person Hans in the following form

insertChildOf "Hans" simon:Person casperFamily:FamilyTree;;

So, input should be parent name, child and the family tree. Ideally it should then return a modified family tree, that is FamilyTree option

What I am struggling with is to incorporating the validate function to make sure it is legal, and a way to insert it properly in the list of children, if the insertion Person is already a parent - maybe as a seperate function.

All help is welcome and very appreciated - thanks! :)


原文:https://stackoverflow.com/questions/27173754
更新时间:2022-01-18 14:01

最满意答案

我很快检查了PRAGMA foreign_keys = ON; 在5.1模拟器和5.1 iPod Touch上都可以正常工作。 正如ccgus所建议的那样,您应该缓存数据库连接。 如果使用队列,只需缓存队列并重新组织代码,这样每次需要使用数据库时都不会创建新的队列。 用你目前的方法,如果你没有真正使用它,而是每次都创造新的东西,那么拥有一个队列有什么意义?

但是回到问题中,正如您已经知道的那样,外键默认是关闭的,所以您需要先启用它。 我设法用PRAGMA foreign_keys = ON;来做到这一点PRAGMA foreign_keys = ON; ,这里是我使用的更多的测试代码:

//create database
NSString* dbPath = [(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
dbPath = [dbPath stringByAppendingPathComponent:@"test.db"];
db = [FMDatabase databaseWithPath:dbPath];
if ([db open]) {
    NSLog(@"Database %@ opened", dbPath);
    //check for foreign_key
    NSString* sql = @"PRAGMA foreign_keys";
    FMResultSet *rs = [db executeQuery:sql];
    int enabled;
    if ([rs next]) {
        enabled = [rs intForColumnIndex:0];
    }
    [rs close];
    if (!enabled) {
        // enable foreign_key
        sql = @"PRAGMA foreign_keys = ON;";
        [db executeUpdate:sql];
        // check if successful
        sql = @"PRAGMA foreign_keys";
        FMResultSet *rs = [db executeQuery:sql];
        if ([rs next]) {
            enabled = [rs intForColumnIndex:0];
        }
        [rs close];
    }
    // do your stuff here, or just cache the connection
} else {
    NSLog(@"Failed to open %@", dbPath);
}

看起来很简单,唯一想到的是你使用executeQuery而不是executeUpdate


I quickly checked and PRAGMA foreign_keys = ON; works fine for me both on 5.1 simulator and 5.1 iPod Touch. As ccgus suggests, you should cache the data base connection. If you use the queue, just cache the queue and reorganize your code so it doesn't create new queue each time you need to use the database. With your current approach, what is the point of having a queue if you don't really use it but create new each time?

But back to the question, as you are already aware, foreign keys are off by default, so you need to first enable it. I managed to do it with PRAGMA foreign_keys = ON;, here is some more of the test code I used:

//create database
NSString* dbPath = [(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
dbPath = [dbPath stringByAppendingPathComponent:@"test.db"];
db = [FMDatabase databaseWithPath:dbPath];
if ([db open]) {
    NSLog(@"Database %@ opened", dbPath);
    //check for foreign_key
    NSString* sql = @"PRAGMA foreign_keys";
    FMResultSet *rs = [db executeQuery:sql];
    int enabled;
    if ([rs next]) {
        enabled = [rs intForColumnIndex:0];
    }
    [rs close];
    if (!enabled) {
        // enable foreign_key
        sql = @"PRAGMA foreign_keys = ON;";
        [db executeUpdate:sql];
        // check if successful
        sql = @"PRAGMA foreign_keys";
        FMResultSet *rs = [db executeQuery:sql];
        if ([rs next]) {
            enabled = [rs intForColumnIndex:0];
        }
        [rs close];
    }
    // do your stuff here, or just cache the connection
} else {
    NSLog(@"Failed to open %@", dbPath);
}

Looks fairly straightforward, the only thing that comes to mind is that you used executeQuery instead of executeUpdate.

相关问答

更多
  • 这是一个链接器错误 - 这意味着,你编译的所有东西都很好,但是一旦将所有编译目标代码打包到可执行文件中,它就无法找到代码中引用的类的实现。 将.m文件拖放到Xcode中的项目源列表中应自动将它们添加到“构建阶段”,但如果你这样做了,并且出现此错误,请检查它们是否在该处:单击顶级项目左侧的源列表获取项目设置,单击下一个窗格中的目标,单击下一个窗格中的“Build Phases”列标题,然后展开“编译源”行。 如果FM文件不在那里,请点击列表底部的+按钮并选择它们。 That's a linker error— ...
  • 使用ALTER TABLE查询来修改表以添加外键约束。 ALTER TABLE yourTable ADD CONSTRAINT FOREIGN KEY (col_in_yourTable) REFERENCES otherTable (col_in_otherTable); ADD CONSTRAINT之后的语法与CREATE TABLE的CONSTRAINT子句基本相同。 Use an ALTER TABLE query to modify the table to add the foreign k ...
  • near "PRAGMA foreign_keys": syntax error 在“附近”之后引用的东西应该是一个单词。 所以在这种情况下,空格字符实际上不是正常的空格字符,而是其他东西,例如不间断的空格。 near "PRAGMA foreign_keys": syntax error The thing quoted after "near" should be a single word. So in this case, the space character is not actually ...
  • 我很快检查了PRAGMA foreign_keys = ON; 在5.1模拟器和5.1 iPod Touch上都可以正常工作。 正如ccgus所建议的那样,您应该缓存数据库连接。 如果使用队列,只需缓存队列并重新组织代码,这样每次需要使用数据库时都不会创建新的队列。 用你目前的方法,如果你没有真正使用它,而是每次都创造新的东西,那么拥有一个队列有什么意义? 但是回到问题中,正如您已经知道的那样,外键默认是关闭的,所以您需要先启用它。 我设法用PRAGMA foreign_keys = ON;来做到这一点PR ...
  • 问题是sharedInstance应该被定义为类中的static ,例如: static let sharedInstance = ModelManager() 然后,只要需要引用此单例,就可以引用ModelManager.sharedInstance (不仅仅是sharedInstance )。 看看这个代码示例,我认为作者希望您将这个sharedInstance实现为全局,但我认为这是一个糟糕的决定。 最好将它作为ModelManager的类属性,以避免污染您的命名空间。 虽然我们在谈论设计选择,但本 ...
  • 我应该引用Project_Forecast表中的Project_Info表中的主键吗? 是 所以我可能会误解这个概念,但是这样做基本上是通过项目ID将每个预测金额返回给项目? 这是正确的 以下是您所描述表格的基本模式: CREATE TABLE project_info ( id serial unique, -- project ID name text, budget int ); CREATE TABLE project_forecast ( id serial u ...
  • 两点意见: 关于使用FMDatabaseQueue外键约束的唯一警告是我建议不要在FMDatabaseQueue事务中使用PRAGMA foreign_keys (即在inTransaction块内)。 PRAGMA foreign_keys 的文档说: 这个pragma是交易中的无操作; 只有在没有挂起的BEGIN或SAVEPOINT时才能启用或禁用外键约束强制。 但是,如果从inDatabase块中执行此pragma,则可以。 您的示例foreign_keys正在执行的foreign_keys 。 外键 ...
  • 您可以考虑包括FMDB头文件( .h ),但不包括.m文件。 这将确保您不会有重复的FMDB链接器引用,但通过包含.h文件,您将能够自己利用FMDB。 您可能要小心,您的头文件对应于与Mapbox使用的FMDB相同的版本。 You might consider including the FMDB header (.h) files, but not the .m files. That will ensure that you won't have duplicative FMDB linker refe ...
  • 如果要检查应用程序sqlite文件中的数据,请在模拟器版本上检查它是否容易。 在初始化数据库的位置,在应用程序中打印documentDirectory路径: // Get Document Directory path of the device. - (NSString*) documentsDirectory{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, Y ...
  • 从技术上讲,你所描述的并不是一对多的关系,而是一种多对多的关系,因为一个Staff记录涉及许多Role记录,但一个Role记录也涉及许多不同的Staff 。 您使用连接表StaffRole是处理关系的典型方式。 这是语义,但它实际上不是组合两个外键的问题,而是仅仅创建第二个键,它是两个键的复合键,也是主键。 因此,您的表将具有两个FOREIGN KEY定义,两个列分别用于两个列,以及两个列中的一个复合PRIMARY KEY定义。 CREATE TABLE StaffRole ( StaffID INT ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。