我第一次玩GHCi,我在编写多行函数时遇到了一些麻烦.我的代码如下:
Prelude> :{
Prelude| let diffSquares lst = abs $ squareOfSums lst - sumOfSquares lst
Prelude| where
Prelude| squareOfSums lst = (fst (sumsAndSquares lst))^2
Prelude| sumOfSquares lst = snd (sumsAndSquares lst)
Prelude| sumsAndSquares = foldl (\(sms,sqrs) x -> (sms+x,sqrs+x^2)) (0,0)
Prelude| :}
Run Code Online (Sandbox Code Playgroud)
它给出以下错误:
<interactive>:1:142: parse error on input `='
Run Code Online (Sandbox Code Playgroud)
有人可以指出我的方向,我错过了什么?
从Haskell 教程:
我们可以根据情况编写整数函数.
-- Compute the sum of the integers from 1 to n.
sumtorial :: Integer -> Integer
sumtorial 0 = 0
sumtorial n = n + sumtorial (n-1)
Run Code Online (Sandbox Code Playgroud)
但是,这是我尝试时会发生的事情:
$ ghci
GHCi, version 8.0.1: http://www.haskell.org/ghc/ :? for help
Prelude> foo 0 = print 999
Prelude> foo n = print n
Prelude> foo 0
0
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
我想创建一个显示列表最后一个元素的函数.这是我的代码:
ghci> let myLast :: [a] -> a
ghci> let myLast [] = error
ghci> let myLast [x] = x
ghci> let myLast (x:xs) = myLast xs
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Run Code Online (Sandbox Code Playgroud)***Exception: Non-exhaustive patterns in function myLast
我知道你在错过案件时会收到这个错误,但我认为我已经包含了所有可能性.有任何想法吗?