haskell - 在 Haskell 中使用带有列表列表的 map 时出现问题

标签 haskell dictionary exponentiation

我正在使用 Haskell 来解决 euler 项目中的问题 99,其中我必须从基指数对列表中找到最大结果。

我想到了这个:

prob99 = maximum $ map ((fst)^(snd)) numbers

数字在表格中的位置:

numbers = [[519432,525806],[632382,518061],[78864,613712]..

为什么这行不通?我需要更改数字格式吗? 这里有没有我没有想到的简单优化,比如更有效的求幂方法?

最佳答案

Give a man a fish, and you'll feed him for a day, teach a man to fish, and you'll feed him for a lifetime.

Jonno,你应该学习如何让 GHC 的错误消息帮助你,以及“undefined drop in”方法(让我们现在专注于此)。

ghci> let numbers = [[519432,525806],[632382,518061]]
ghci> -- so far so good..
ghci> let prob99 = maximum $ map ((fst)^(snd)) numbers

<Bam! Some type error>

ghci> -- ok, what could have gone wrong?
ghci> -- I am pretty sure that this part is fine:
ghci> let prob99 = maximum $ map undefined numbers
ghci> -- yes, it is fine
ghci> -- so the culprit must be in the "((fst)^(snd))" part
ghci> let f = ((fst)^(snd))

<Bam! Some type error>

ghci> -- whoa, so this function never makes sense, not just where I used it..
ghci> -- is it doing what I think it is doing? lets get rid of those braces
ghci> let f = fst ^ snd

<Bam! Same type error>

ghci> -- yeah I got my syntax right alright
ghci> -- well, can I exponent fst?
ghci> let f = fst ^ undefined

No instance for (Num ((a, b) -> a))
  arising from a use of '^' at <interactive>:1:8-22
Possible fix: add an instance declaration for (Num ((a, b) -> a))
In the expression: fst ^ undefined
In the definition of 'f': f = fst ^ undefined

ghci> -- duh, fst is not a Num
ghci> -- this is what I wanted:
ghci> let f x = fst x ^ snd x
ghci> -- now lets try it
ghci> let prob99 = maximum $ map f numbers

<Bam! Some type error>

ghci> -- still does not work
ghci> -- but at least f makes some sense now
ghci> :t f

f :: (Num a, Integral b) => (a, b) -> a

ghci> -- lets find an example input for it
ghci> head numbers

[519432,525806]

ghci> :t head numbers

head numbers :: [Integer]

ghci> -- oh, so it is a list of two integers and not a tuple!
ghci> let f [a, b] = a ^ b
ghci> let prob99 = maximum $ map f numbers
ghci> -- no error?
ghci> -- finally I got the types right!

关于haskell - 在 Haskell 中使用带有列表列表的 map 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1496614/

相关文章:

c - 实现基于整数的幂函数 pow(int, int) 的最有效方法

haskell - 无法在 nixos 中安装 ghc

c# - 如何创建一个字典列表作为另一个字典的值?

haskell - 当使用 `DerivingVia` ` 等光学类型时,无法在 `Prism' 期间进行强制

Perl `map` : When to use EXPR vs. block 形式?

c# - 将 IEnumerable 转换为字典以提高性能?

java - ^ 运算符在 Java 中的作用是什么?

c++ - 带加法的指数算法

Haskell IO 函数 -> 类型匹配错误

Haskell 示例通常不起作用