[英]How to program haskell with ghci?
我一直在閱讀一些材料,在這里我有一個問題:我看到一段代碼是這樣的:
>getNthElem 1 xs = head xs
>getNthElem n [] = error "'n' is greater than the length of the list"
>getNthElem n xs
> | n < 1 = error "'n' is non-positive"
> | otherwise = getNthElem (n-1) (tail xs)
我應該將所有這些行完全相同地輸入到ghci中,還是應該創建一個.hs文件並將其放入,然后將其加載到ghci中?
有兩種方法可以做到這一點:
通過將標志設置為ghci,在ghci中使用多行模式:
Prelude> :set +m Prelude> let getNthElem 1 xs = head xs Prelude| getNthElem n [] = error "error1" Prelude| getNthElem n xs Prelude| | n < 1 = error "error2" Prelude| | otherwise = getNthElem (n-1) (tail xs) Prelude| Prelude>
創建一個文件並將其作為模塊加載,以訪問其中定義的類型和函數
Prelude> :l myModule.hs
和文件內容:
getNthElem :: Int -> [a] -> a getNthElem 1 xs = head xs getNthElem n [] = error "'n' is greater than the length of the list" getNthElem n xs | n < 1 = error "'n' is non-positive" | otherwise = getNthElem (n-1) (tail xs)
我建議使用第二個選項,因為很容易在GHCI中的多行模式下弄亂縮進。 另外,在開始定義函數體之前,養成添加類型簽名的習慣。
你可以寫一行:
> let getNthElem 1 xs = head xs; getNthElem n [] = error "'n' is greater than the length of the list"; getNthElem n xs | n < 1 = error "'n' is non-positive" | otherwise = getNthElem (n-1) (tail xs)
不要忘記寫分號而不是換行符,並在開頭添加let
word。
您也可以使用多線制:
> :{
| let getNthElem 1 xs = head xs
| getNthElem n [] = error "'n' is greater than the length of the list"
| getNthElem n xs
| | n < 1 = error "'n' is non-positive"
| | otherwise = getNthElem (n-1) (tail xs)
| :}
>
最簡單的方法是創建一個名為example.hs
的文件,然后在命令行啟動ghci並加載文件
$ ghci
GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help
Prelude> :load example.hs
[1 of 1] Compiling Main ( example.hs, interpreted )
Ok, module loaded: Main.
*Main>
或者,您可以在啟動ghci時加載該文件
$ ghci example.hs
GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help
[1 of 1] Compiling Main ( example.hs, interpreted )
Ok, module loaded: Main.
*Main>
請注意,每行開頭的>
表示您的文件是有文化的Haskell文件,即它應該具有擴展* .lhs而不是* .hs。 您應該將文件重命名為* .lhs或刪除每行開頭的>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.