添加小数类型的问题

时间:2016-06-27 17:29:36

标签: haskell

我正在尝试定义一个函数,要求我将一个小数类型添加到double中,但我似乎收到错误。

epsilon = 0.0000001
dif :: (Fractional a) => (a->a) -> a -> a

dif f x = (f(x+epsilon)-f(x))/epsilon

Haskell似乎在解释x + epsilon时遇到了麻烦,但考虑到x在函数声明中定义为Fractional类型并且epsilon是double(它是Fractional类型类的一部分?

这是我得到的错误:

Couldn't match expected type ‘a’ with actual type ‘Double’
  ‘a’ is a rigid type variable bound by
      the type signature for dif :: Fractional a => (a -> a) -> a -> a
      at dif.hs:3:8
Relevant bindings include
  x :: a (bound at dif.hs:5:7)
  f :: a -> a (bound at dif.hs:5:5)
  dif :: (a -> a) -> a -> a (bound at dif.hs:5:1)
In the second argument of ‘(+)’, namely ‘epsilon’
In the first argument of ‘f’, namely ‘(x + epsilon)’

谢谢。

1 个答案:

答案 0 :(得分:6)

epsilon :: Fractional a => a 一个适当的多态类型签名:

using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Management.Automation;

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string cmdLetName = "Get-Content";
            Collection<PSObject> PSOutput;
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddCommand("Get-Command");
                PowerShellInstance.AddParameter("Name", cmdLetName);
                PSOutput = PowerShellInstance.Invoke();
            }

            foreach(var item in PSOutput)
            {
                var cmdLetInfo = item.BaseObject as System.Management.Automation.CmdletInfo;
                var defaultParamSet = cmdLetInfo.ParameterSets.Where(pSet => pSet.IsDefault == true).FirstOrDefault();

                Console.WriteLine(String.Format("Default ParameterSet for {0}.  (*) Denotes Mandatory", cmdLetName));
                foreach (var param in defaultParamSet.Parameters.OrderByDescending(p => p.IsMandatory))
                {
                    if (param.IsMandatory)
                        Console.WriteLine(String.Format("\t {0} (*)", param.Name));
                    else
                        Console.WriteLine(String.Format("\t {0}", param.Name)); ;
                }
            }

            Console.ReadLine();
        }
    }
}

您可能也喜欢What is the monomorphism restriction?中的解释。