(Num a)不作为应用函数推断

时间:2016-12-20 14:41:33

标签: haskell

我将这个简单的函数示例作为应用程序:

$> :t (+) <$> Just (+5) <*> Just(+3)
(+) <$> Just (+5) <*> Just(+3)
  :: (Num (a -> a), Num a) => Maybe (a -> a)

所以预期的返回值应该是Maybe (a -> a),基本上是包含在Maybe上下文中的函数。我将它传递给Monad以便能够使用它,在此:

$> (+) <$> Just (+5) <*> Just(+3) >>= (\x -> Just (x $ 7))

<interactive>:116:1: error:
    • Non type-variable argument in the constraint: Num (b -> b)
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        it :: forall b. (Num (b -> b), Num b) => Maybe b

但正如您所看到的,我认为有一个错误与无法推断类型变量a的类型的事实有关,在这种情况下是Num a

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:9)

private void MaakExcelFile() { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); if (saveFileDialog1.ShowDialog() == DialogResult.OK) { //string zonderspecialchars = RemoveSpecialCharacters(saveFileDialog1.FileName); copyAlltoClipboard(); Microsoft.Office.Interop.Excel.Application xlexcel; Microsoft.Office.Interop.Excel.Workbook xlWorkBook; Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; xlexcel = new Microsoft.Office.Interop.Excel.Application(); xlexcel.Visible = true; xlWorkBook = xlexcel.Workbooks.Add(); xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1]; CR.Select(); xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true); // string zonderspecialchars = RemoveSpecialCharacters(filenaam); try { xlWorkBook.SaveAs(@"" + saveFileDialog1.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } catch (Exception e) { throw e; } } } 中,(+) <$> Just (+5) <*> Just(+3)(<$>)仅涉及(<*>)上下文,而不涉及函数1。它没有表达您的意图的标志是推断类型:

Maybe

请注意(+) <$> Just (+5) <*> Just(+3) :: (Num (a -> a), Num a) => Maybe (a -> a) 约束。它显示是因为您尝试将Num (a -> a)直接应用于(+)中的(+5)功能,这不是您想要的。

您需要做的是处理两个应用背景层。一种方便的方法是通过the Compose newtype

Just (+5)

GHCi> import Data.Functor.Compose GHCi> :t getCompose ((+) <$> Compose (Just (+5)) <*> Compose (Just (+3))) getCompose ((+) <$> Compose (Just (+5)) <*> Compose (Just (+3))) :: Num a => Maybe (a -> a) 的相关实例可确保Composefmap正确处理这两个上下文层。在 base 中引用源代码的相关位:

(<*>)