如何将这些函数用于“列表”类型

时间:2016-11-25 20:35:23

标签: haskell functional-programming

我试图了解如何在Prelude中使用以下Haskell代码(可用here)中定义的函数。

var newState = product.concat(this.state.products);

我使用module List where data List a = Nil | Cons a (List a) listLength :: List a -> Int listLength Nil = 0 listLength (Cons x xs) = 1 + listLength xs {- listHead :: List a -> Maybe a listHead Nil = Nothing listHead (Cons x xs) = Just x listTail :: List a -> Maybe (List a) listTail Nil = Nothing listTail (Cons x xs) = Just xs -} listHead :: List a -> a listHead (Cons x xs) = x listTail :: List a -> List a listTail (Cons x xs) = xs listFoldl :: (a -> b -> a) -> a -> List b -> a listFoldl f c Nil = c listFoldl f c (Cons x xs) = listFoldl f (f c x) xs listFoldr :: (a -> b -> b) -> b -> List a -> b listFoldr f c Nil = c listFoldr f c (Cons x xs) = f x (listFoldr f c xs) 命令加载了它。

然后是我尝试使用ghci List.hs的方式。

listHead

或者喜欢以下内容:

*List> listHead (List 1:2:[])

<interactive>:7:11: Not in scope: data constructor `List'

有人可以解释如何在ghci中使用此代码吗?谢谢!

2 个答案:

答案 0 :(得分:3)

ws.write(rowx, colx, value.decode('utf-8')) 运算符和:结构特定于Haskell的内置列表类型,即您只能使用它们来构造某种类型[]的值。但是,此处的函数不处理此标准列表类型,而是使用本地定义的[a]容器。要构建此类列表,您需要将每个List替换为:,将每个Cons替换为[]。由于Nil不是中缀运算符,因此首先需要将Cons重写为a:b,这有点复杂。例如,(:) a b列表[Int]变为1:2:[],相当于(:) 1 ((:) 2 [])

然后可以将这些自定义列表提供给任何这些功能。

Cons 1 (Cons 2 Nil)

当然这很难看,但*List> listHead $ Cons 1 (Cons 2 Nil) 1 类型仅用于教育目的。实际上,您将使用标准List类型,或使用更好的构造函数。例如,您可以自己定义中缀构造函数,如[]

:

你可以这样做

infixr 6 :&
data List' a = N | a :& List' a

或者,您可以让GHC接受自定义列表类型的*List> list'Head $ 1 :& 2 :& N 语法:

[]

然后

{-# LANGUAGE OverloadedLists, TypeFamilies #-}

import GHC.Exts (IsList(..))

instance  IsList (List l) where
  type Item (List l) = l
  fromList [] = Nil
  fromList (a:l) = Cons a $ fromList l

答案 1 :(得分:2)

您应该使用以下定义的ListCons 数据构造函数构建自定义Nil

data List a = Nil
            | Cons a (List a)

发生了第一个错误Not in scope: data constructor `List',因为您无法使用List来构建值(List是一个类型构造函数,List a是一个类型)。你真正想要的是:

listHead (Cons 1 (Cons 2 Nil)))

发生第二个错误Couldn't match expected type `List a0' with actual type `[Char]',因为您尝试使用常规列表构造函数(:)[]来构建List Char值。您应该使用Cons代替(:)Nil而不是[]