티스토리 뷰

Haskell

내가 만든 .hs 파일 사용하기

newpolaris 2011. 1. 18. 02:26
초보자를 위한 글 : http://learnyouahaskell.com/modules#making-our-own-modules

간단하게 "Pairs.hs" 파일 안의 pair 란 이름의 함수를 다른 파일에서도 사용하고 싶다면,
( 함수명과 모듈명은 상관 없다; 여기서는 그냥 Pairs, pairs 인 것 )
module Pairs where

pairs :: [a] -> [(a,a)]
pairs a = zip a (tail a)
위 같이 작성하여 "Pairs.hs" 파일로 저장하면 된다.
주의 할점은
1. 모듈명은 대문자로 시작해야 한다. ( module 키워드 다음에 오는 단어)
2. 하나의 파일에 오직 하나의 모듈

윈도우 환경에서 GHCi의 경우 소문자인 "pairs.hs"도 동작하긴 하나 가이드에는 module 명과 동일하게 할 것을 요구하고 있다
"Since the module name must begin with a capital letter, the file name must also start with a capital letter."

이 모듈을 사용 하는 파일에서는 아래와 같이 "import"를 사용하면 된다.
import Pairs


하지만 이렇게 module Pairs where 라고 선언하면 erlang의 "export all" 과 같이
해당 모듈의 모든 함수가 import 한 곳에서 보이게 된다
대충 간단하긴 하지만 내부적으로 사용할 함수와 밖에서 보이게될 함수와 구분을 짓고 싶다면,
module MyModule (remove_one, add_two) where
 
add_one a = a + 1
add_two a = a + 2
remove_one a = a - 1
만약 import 하는 측에서 몇개만 선택적으로 import 하고 싶은 경우엔,
-- import only the functions add_one from MyModule
import MyModule (add_one)

자세한 사항은 http://en.wikibooks.org/wiki/Haskell/Modules 참조

'Haskell' 카테고리의 다른 글

Programming in Haskell notes  (0) 2011.01.24
jolly jumper  (0) 2011.01.18
Programming in Haskell (6) ch3. Exercise  (0) 2011.01.17
Programming in Haskell (5) ch2. Exercise  (0) 2011.01.14
Programming in Haskell (4)  (0) 2011.01.14
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크