gpt4 book ai didi

haskell - 也许您还没有对函数应用足够的参数?

转载 作者:行者123 更新时间:2023-12-02 16:31:09 26 4
gpt4 key购买 nike

我正在大学的类(class)中学习 Haskell,有一个考试练习,我们需要定义一个函数,该函数接受函数列表 [(Int ->Int)] 和另一个 Int 类型的参数并返回一个 Int。所以类型应该是

compose :: [(Int ->Int)] -> Int -> Int.

该函数应从左到右返回列表中函数的组合,并将其应用于第二个参数。我尝试了以下方法:

compose :: [(Int -> Int)] -> Int -> Int
compose [] x = x
compose (f:fs) x
|fs == [] = f x
|f : (compose fs x)

但是编译器抛出错误:

003Exam.hs:24:22:
Couldn't match expected type ‘Int’ with actual type ‘[Int -> Int]’
In the expression: f : (compose fs x)
In an equation for ‘compose’:
compose (f : fs) x
| fs == [] = f x
| otherwise = f : (compose fs x)

003Exam.hs:24:28:
Couldn't match expected type ‘[Int -> Int]’ with actual type ‘Int’
In the second argument of ‘(:)’, namely ‘(compose fs x)’
In the expression: f : (compose fs x)

如果我保留最后一行,例如:

compose :: [(Int -> Int)] -> Int -> Int
compose [] x = x
compose (f:fs) x
|fs == [] = f x

然后我也收到一个错误 - 这是我真的不明白的错误:

003Exam.hs:23:13:
No instance for (Eq (Int -> Int))
(maybe you haven't applied enough arguments to a function?)
arising from a use of ‘==’
In the expression: fs == []
In a stmt of a pattern guard for
an equation for ‘compose’:
fs == []
In an equation for ‘compose’: compose (f : fs) x | fs == [] = f x

如果您能提供任何帮助来澄清我做错了什么,我会很高兴。

最佳答案

首先, (:) 仅用于在列表前面添加元素(或与这些元素进行模式匹配),因此您必须替换

f : compose fs x

f (compose fs x)

接下来,您必须在防护中使用 Bool 类型的表达式或模式匹配:

| fs == []  = -- this line is still wrong, see below
| otherwise = f (compose f xs)

但是,函数没有 Eq 实例。两个函数的等价性是不可判定的(一般情况下),因此使用 null::[a] -> Bool 而不是 (==)::Eq a => [a] -> [a] -> bool 型:

compose :: [(Int -> Int)] -> Int -> Int
compose [] x = x
compose (f:fs) x
| null fs = f x
| otherwise = f (compose fs x)

由于 compose [] xx 相同,您甚至可以删除检查:

compose :: [(Int -> Int)] -> Int -> Int
compose [] x = x
compose (f:fs) x = f (compose fs x)

练习

  • 扩展compose [(+1), (+2)] 1(用其定义替换它)而不删除中间术语。你注意到其中的规律了吗?
  • 这个模式是否让您想起库函数?
  • 尝试使用该库函数来编写 compose

关于haskell - 也许您还没有对函数应用足够的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35606068/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com