如何与Haskell中的代数类型进行模式匹配 [英] How to Pattern Match With Algebraic Types in Haskell

查看:126
本文介绍了如何与Haskell中的代数类型进行模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理的任务的目标是创建一系列不同的函数,这些函数涉及搜索名为Trie的数据类型,其中构造函数被定义为

< pre $ data Trie = MakeTrie Char [Trie]派生方程式

我打算首先构建简单的函数,以便我可以找出如何下降这个Trie,但似乎模式匹配不起作用。

  test :: Trie  - > Bool 
测试t
| t == MakeTrie'。'[_] = True
|否则= False

我得到一个错误,指出找到了一个洞并且相关的绑定包括t ::特里。我怎样才能让翻译知道[_]代表尝试列表?我这样做的原因是因为如果我不使用模式匹配,我不知道如何继续降低我的Trie。

解决方案 div>

您应该在 Learn You Haskell中检出函数语法章节

(特别是关于模式匹配的第一部分)。



这是你在这个例子中如何在Haskell中进行模式匹配:

  test :: Trie  - > Bool 
test(MakeTrie'。'_)= True
test _ = False



<测试:

  Prelude>测试(MakeTrie'。'[])
True
Prelude>测试(MakeTrie'a'[])
False


The goal of the assignment I am working on is to create a bunch of different functions that involve searching a data type called a Trie, in which the constructor is defined as

data Trie = MakeTrie Char [Trie] deriving Eq

I am tying to first build simple functions so I can figure out how to descend this Trie, but it seems like pattern matching is not working.

test :: Trie -> Bool
test t
    | t == MakeTrie '.' [_] = True
    | otherwise = False

I get an error stating that a hole was found and that relevant bindings include t :: Trie. How can I let the interpreter know that [_] represents a list of Tries? The reason I am doing this is because I have no idea how else do go ahead descending my Trie later if I don't use pattern matching.

解决方案

You should checkout the function syntax chapter in Learn You A Haskell (particularly the first section on pattern matching).

This is how you do pattern matching in Haskell for this example:

test :: Trie -> Bool
test (MakeTrie '.' _) = True
test _ = False

Testing:

Prelude> test (MakeTrie '.' [])
True
Prelude> test (MakeTrie 'a' [])
False

这篇关于如何与Haskell中的代数类型进行模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆