Haskell:NonEmpty

时间:2017-07-31 19:24:10

标签: haskell

我正在学习Haskell并试图了解NonEmpty的工作原理。我写了以下代码。

module Mm (main, Bb, g) where

import Data.List.NonEmpty

g :: NonEmpty Integer -> NonEmpty Integer
g  = fmap (+9) 
main = g

它编译,但是当我这样做时:

b= nonEmpty [2,3]
main b

出现错误。我不明白我在哪里做错了什么!

编辑:我收到以下错误:

couldn't match expected type 'NonEmpty Integer' with actual type 'Maybe 
(NonEmpty Integer)'.  In the first argument of 'main' namely 'b'.
In the expression: main b
In an equation for 'it' : it = main b

1 个答案:

答案 0 :(得分:3)

查看nonEmpty的类型。 nonEmpty []的结果应该是什么?  您收到类型错误,因为nonEmpty 返回Maybe (NonEmpty a),或者它是部分函数(如果您尝试过,可能会在运行时崩溃)访问价值)。

解决方案

有几种方法可以解决问题。一种是使用maybe根据结果选择一个动作:

maybe (Left "List is empty") (Right . main) $ b

另一种方法是对结果进行模式匹配,假设它永远不会Nothing。如果这个假设被证明是错误的,那么你的程序将在运行时崩溃:

let (Just b) = nonEmpty [2,3] in main b

我忽略了第三个选择是直接使用NonEmpty的构造函数:

main $ 2 :| [3]

这可能是您正在寻找的解决方案。由于我上面所说的原因,通过列表的路线只是一个恼人的绕道而已。

相关问题