首页 > 解决方案 > 使用运算符 (/x) 映射函数的问题

问题描述

所以我有一个函数的结果,它给定一个整数列表,将一个整数减去一个整数到列表中的所有数字,然后我想在这种情况下将新列表除以 x 12。如果我做第一段编码它给我一个错误,但如果我做第二个,它是可能的。我该怎么做,为什么它会给我一个错误?

let xs = [23,32,1,3]
map (/12) xs

map(/12) [23,32,1,3]

potenciasPor12 xs = map (/12) xs

这是我得到的错误

<interactive>:176:1:
No instance for (Fractional Int)
  arising from a use of ‘potenciasPor12’
In the expression: potenciasPor12 xs
In an equation for ‘it’: it = potenciasPor12 xs

标签: functionhaskellmapping

解决方案


如果设置了单态限制(在较新的 GCHi 中默认关闭,但在编译代码中打开),则xs默认为[Int]而不是更通用的类型Num a => [a],该类型适用于(/)运算符。

(至少在 GHCi 8.4.1 中,它似乎默认为Integer而不是Int.)

% ghci
GHCi, version 8.4.1: http://www.haskell.org/ghc/  :? for help
Prelude> let xs = [1,2]
Prelude> :t xs
xs :: Num a => [a]
Prelude> :set -XMonomorphismRestriction
Prelude> let ys = [1,2]
Prelude> :t ys
ys :: [Integer]

始终提供明确的类型签名以确保:

% ghci -XMonomorphismRestriction
GHCi, version 8.4.1: http://www.haskell.org/ghc/  :? for help
Prelude> let xs = [23,32,1,3] :: Num a => [a]
Prelude> :t xs
xs :: Num a => [a]
Prelude> map (/12) xs
[1.9166666666666667,2.6666666666666665,8.333333333333333e-2,0.25]

推荐阅读