2013-07-06 5 views
1

나는 clojure에서 텍스트 모험을하고 있습니다. 내가 고민하고 어디Clojure에서 전역 변수에 액세스하십시오.

이입니다

(ns records) 


(defrecord Room [fdesc sdesc ldesc exit seen]) 

(defrecord Item [name location adjective fdesc ldesc sdesc flags action ]) 

(def bedroom (Room. "A lot of text." 
        nil 
        "some text" 
        '(("west" hallway wearing-clothes? wear-clothes-f)) 
        false)) 

(def hallway (Room. "description of room." 
          nil 
          "short desc of room." 
          '(("east" bedroom) ("west" frontdoor)) 
          false)) 

(def location (ref bedroom)) 

(defn in? 
    "Check if sequence contains item." 
    [item lst] 
    (some #(= item %) lst)) 

(defn next-location 
    "return the location for a entered direction" 
    [direction ] 
    (second (first (filter #(in? direction %) (:exit @location))))) 

(defn set-new-location 
    "set location parameter to new location." 
    [loc] 
    (dosync (ref-set location loc))) 

내 문제는 VAR 위치를 업데이트하는 것입니다.

(set-new-location hallway)을 입력하면 제대로 작동합니다. 위치가 새 방으로 설정되고 해당 필드에 액세스 할 수 있습니다. 그러나 내가해야 할 일은 방의 출구 필드에서 다음에 가능한 출구를 읽는 것입니다. 그러나 (set-new-direction (next-exit "west")) 위치에 복도라고 표시되어 있지만 변수 "복도"를 가리 키지는 않습니다.

CL에서 (기호 - 값 복도)를 사용합니다. 어떻게 Clojure에서이 작업을 수행 할 수 있습니까?

EDIT : 대략 30 개 위치를 스케치 했으므로 각 행마다 20 행으로 하나의 맵에 배치하기가 너무 힘들어서 var-per-location을 사용하고 싶습니다.

답변

3

@(resolve sym)symbol-value 작업 공정으로 사용할 수 있습니다. 실제로 수행 할 작업은 현재 네임 스페이스 (use/require :refer과 함께 가져온 Var 일 수 있음)에서 sym 기호로 명명 된 Var을 찾아 해당 값을 추출하는 것입니다. (당신을

(def locations {:hallway ... :bedroom ...}) 

:. 당신은 바르가에서보고 된 네임 스페이스를 제어하려는 경우

또한 바르 당 위치에 사용할 수 ns-resolve를 참조 아니라 어딘가지도에 위치를 저장 런타임시 새 위치를 추가 할 수 있도록 Ref에이 맵을 넣을 수도 있습니다.

+0

어떻게 작동합니까? '(ref-location location @ (침실 정리))'를 시도하면 ClassCastException 레코드가 생깁니다. clojure.lang.Symbol clojure.core/ns-resolve (core.clj : 3954)'로 보낼 수 없습니다. – martin

+0

'bedroom'을'resolve'에 전달하려면'@ (resolve the bedroom)'(인용문에주의하십시오)라고 써야합니다. 물론, 그런 특별한 기호를 하드 와이어하면, 그 일을 할 필요가 없으며 단지'침실 '이라고 쓸 수 있습니다; 그러나 심볼이'next-location'에 대한 호출과 같이 동적으로 계산되면 추가 인용은 필요하지 않습니다 :'@ (resolve (next-location "west"))'. –

관련 문제