【问题标题】:Why cant i define a constant and than use it in a function in Haskell?为什么我不能定义一个常量而不是在 Haskell 的函数中使用它?
【发布时间】:2013-04-22 10:48:55
【问题描述】:
    element ::Int->Int->[[Int]]-> Int
    element z s m= m!!z!!s
    maxIndex :: Int
    maxIndex = 6  

    matrix :: [[Int]] -> Int -> Int -> Int -> Int
    matrix a row column maxIndex = if maxIndex < length a then error "Out of range"
         else if (row-1<0 || row-1>maxIndex)||(column-1<0 || column-1>maxIndex) then error "Out of range"
         else element (row-1) (column-1) a

我在哪里犯了错误?我希望我的程序采用我的 maxIndex 常量,这样用户就不必输入 maxIndex 的值?

【问题讨论】:

    标签: function haskell constants


    【解决方案1】:

    maxIndex 已经是矩阵的词法范围内定义的标识符。就像 element 一样,你不需要做任何特别的事情来使用它,所以你可以说:

    matrix :: [[Int]] -> Int -> Int -> Int
    matrix a row column = ...
    

    【讨论】:

    • 不,maxIndex 不是函数。不过,其余的仍然是正确的。
    • 函数是A -&gt; B 类型的东西(适用于AB 类型)。函数可以应用于参数以产生结果。 Int 不是函数。
    • @kosmikus:按照这个定义,readLn 也不是一个函数。但是如果不是函数,你怎么称呼它。这当然不是一个常数。
    • @tauli 在某种程度上它是一个常数。这是一个 IO 操作,执行时从标准输入读取一行输入,调用适当的 read 函数将输入转换为请求类型的值,并返回转换结果(或失败,如果标准输入损坏, 输入不是read, ...) 的合适参数。换句话说,它是一个函数,因为在底层,read 函数作为参数传递给readLn
    • 在我们重新讨论所有旧论点之前,也许是再次指出conal.net/blog/posts/everything-is-a-function-in-haskell 的好时机。
    猜你喜欢
    • 2020-05-17
    • 2015-07-10
    • 2017-01-11
    • 2021-12-21
    • 2013-09-18
    • 1970-01-01
    • 2016-07-09
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多