为什么这个函数在runghc中起作用而在ghci中不起作用?

时间:2015-05-05 03:26:59

标签: haskell

如果我运行以下文件:

ll []     = 0
ll (x:xs) = 1 + ll xs
main = putStrLn (show (ll [2,2,2]))

使用runghc,它可以工作并打印3。

在ghci,otoh,我得到:

ghci> let ll [] = 0
ghci> let ll (x:xs) = 1 + ll xs
ghci> ll [3,4,43,9]
*** Exception: <interactive>:23:5-25: Non-exhaustive patterns in function ll

上述代码无法在ghci中运行的原因是什么?需要做哪些改变才能使其发挥作用?

1 个答案:

答案 0 :(得分:2)

运行ghci时,您键入的所有内容都在IO monad中,因此您需要额外的let ll (x:xs) = 1 + ll xs s(您确实包含了它)。然而,这会导致复杂化。

每次使用&#34;让&#34;时,您将重新定义该功能。唯一重要的是最后一个

let ll [] = 0

所以你错过了另一个案例

let ll [] = 0; ll (x:xs) = 1 + ll xs

您可以在同一行定义两者,但是这样

-- Players
CREATE TABLE player
    (`id` int primary key auto_increment, `name` varchar(255))
;

-- Games
CREATE TABLE game
    (`id` int primary key auto_increment, `name` varchar(255))
;

-- Items and what game they belong to
CREATE TABLE item
    (`id` int primary key auto_increment, `game_id` int, `name` varchar(255))
;

-- What games players are playing
CREATE TABLE player_game
    (`player_id` int, `game_id` int)
;

-- What items players have
CREATE TABLE player_item
    (`player_id` int, `item_id` int, index(`player_id`))
;