1

私は現実世界の haskell に従っています。第 2 章に演習があります。

私の解決策は

lastButOne xs = if null xs || null (tail xs)
                then []
                else if null (tail (tail xs))
                     then head xs
                     else lastButOne (tail xs)

[] 以外は動作せず、このようなエラーが発生します。

*Main> lastButOne []
[]
*Main> lastButOne [1, 2]

<interactive>:5:13:
    No instance for (Num [a0]) arising from the literal `1'
    Possible fix: add an instance declaration for (Num [a0])
    In the expression: 1
    In the first argument of `lastButOne', namely `[1, 2]'
    In the expression: lastButOne [1, 2]

私はかなりの初心者で、不可解なエラー メッセージを理解していません。何か案は?

4

3 に答える 3

1

これについては、パターンマッチングの方がエレガントだと思います...私自身、Haskellの初心者です(ずっと前に少し読んだだけです):

lastButOne ([]) = []
lastButOne (beforeLast:last:[]) = beforeLast
lastButOne (x:xs) = lastButOne xs

これがエラーの説明ではないことは承知していますが、問題をまったく回避することが最善の解決策である場合もあります。

于 2013-06-06T14:34:57.900 に答える